aboutsummaryrefslogtreecommitdiff
path: root/extensions/chrome/common.js
blob: 30dc55af29f23c6a6c9738325dcb050fe8777d3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
function init() {
  // receive messages from webpage
  chrome.runtime.onMessageExternal.addListener(receiveMessage);
}
function receiveMessage(msg, sender, sendResponse) {
  if (msg.cmd == "injection_result") {
    var obj = Injections.get(msg.id);
    if (obj) obj.addResponse(sender.tab.id, msg.data);
  }
}
function extend(dest, source) {
  for (var i in source) {
    dest[i] = source[i];
  }
}
function getWebSocket() {
  return window.WebSocket || window.MozWebSocket;
}
function print() {
  var msgs = [], i, tmp;
  for (i = 0; i < arguments.length; i++) {
    if (arguments[i] instanceof Error) tmp = [arguments[i], arguments[i].stack];
    else tmp = arguments[i];
    msgs.push(tmp);
  }

  try {
    console.log.apply(console, msgs);
  } catch(e) {}
}
function getExtensionId() {
  return chrome.i18n.getMessage("@@extension_id");
}
function getVKTabs(callback) {
  var vkTabs = [];
  chrome.tabs.query({}, function(tabs) {
    for (var i = 0; i < tabs.length; i++) {
      var tab = tabs[i];
      if (tab.url.match(new RegExp('https?://vk.com/.*', 'gi'))) {
        vkTabs.push(tab);
      }
    }
    callback(vkTabs);
  });
}
function executeCommand(cmd) {
  var injId = Injections.getNextId();
  var code_inj = "var el = document.createElement('script'); el.src = chrome.extension.getURL('inject_and_return.js'); document.body.appendChild(el); var el1 = document.createElement('script'); el1.textContent = 'window.__vkpc_extid=\""+getExtensionId()+"\"; window.__vkpc_injid="+injId+"'; document.body.appendChild(el1)";
  var code_exec = "var el = document.createElement('script'); el.src = chrome.extension.getURL('inject_exec.js'); document.body.appendChild(el); var el1 = document.createElement('script'); el1.textContent = 'window.__vkpc_cmd=\""+cmd+"\"'; document.body.appendChild(el1)";

  getVKTabs(function(tabs) {
    if (!tabs.length) return;

    var injResponses, activeTabId = null;
    var onDone = function() {
      var ok = {nowPlaying: null, lsSource: null, recentlyPlayed: null, active: activeTabId, last: null};
      var results = injResponses.results, lsSource = injResponses.lsSource;
      
      for (var i = 0; i < results.length; i++) {
        var data = results[i].data, id = results[i].tab;
        ok.last = id;
        
        if (data.havePlayer && (data.isPlaying || typeof data.trackId == 'string')) {
          ok.recentlyPlayed = id;
        }
        if (data.isPlaying) {
          ok.nowPlaying = id;
        }
        if (lsSource && lsSource == data.instanceId) {
          ok.lsSource = id;
        }
      }
      injResponses.unregister();

      var rightId = ok.nowPlaying || ok.lsSource || ok.recentlyPlayed || ok.active || ok.last;
      if (rightId) {
        chrome.tabs.executeScript(rightId, {code: code_exec});
      }
    };
    injResponses = new InjectionResponses(injId, tabs.length, onDone);

    for (var i = 0; i < tabs.length; i++) {
      if (tabs[i].active) activeTabId = tabs[i].id;
      chrome.tabs.executeScript(tabs[i].id, {
        code: code_inj
      });
    }
  });
}

var Injections = {
  id: 0,
  objs: {},
  getNextId: function() {
    return ++this.id;
  },
  get: function(id) {
    return this.objs[id] || false;
  },
  register: function(id, obj) {
    this.objs[id] = obj;
  },
  unregister: function(id) {
    if (this.objs[id] !== undefined) delete this.objs[id];
  }
};

var WSClient = new function() {
  var STATUS_NONE = 0, STATUS_OK = 1, STATUS_ERR = 2;
  var _ws = getWebSocket(), ws;
  var _status = STATUS_NONE; 
  var ping_timer, reconnect_timer;

  if (!_ws) return;

  function setTimers() {
    ping_timer = setInterval(function() {
      if (ws) ws.send("PING");
    }, 30000);
  }
  function unsetTimers() {
    clearInterval(ping_timer);
  }

  function connect() {
    _status = STATUS_NONE;

    print("[connect]");
    ws = new _ws("ws://localhost:52178", "signaling-protocol");
    ws.onopen = function() {
      _status = STATUS_OK;
      setTimers();
    };
    ws.onerror = function() {
      unsetTimers();
      if (_status != STATUS_ERR) {
        _status = STATUS_ERR;
        tryToReconnect();
      }
    }
    ws.onclose = function() {
      unsetTimers();
      if (_status != STATUS_ERR) {
        _status = STATUS_ERR;
        tryToReconnect();
      }
    };
    ws.onmessage = function(e) {
      onCommand(e.data);
    };
  }
  function tryToReconnect() {
    print("[tryToReconnect]");

    clearTimeout(reconnect_timer);
    reconnect_timer = setTimeout(connect, 5000);
  }
  function onCommand(msg) {
    executeCommand(msg);
  }

  connect();
};

function InjectionResponses(id, count, callback) {
  this.id = id;
  this.results = [];
  this.lsSource = null;
  this.maxCount = count;
  this.callback = callback || function() {};

  Injections.register(this.id, this);
}
extend(InjectionResponses.prototype, {
  addResponse: function(id, response) {
    this.results.push({tab: id, data: response});
    if (!this.lsSource && response && response.lastInstanceId) this.lsSource = response.lastInstanceId;
    if (this.results.length == this.maxCount) {
      this.callback();
    }
  },
  unregister: function() {
    Injections.unregister(this.id);
  }
});

init();