Skip to content

Instantly share code, notes, and snippets.

@mcxiaoke
Created May 25, 2011 14:57
Show Gist options
  • Save mcxiaoke/991123 to your computer and use it in GitHub Desktop.
Save mcxiaoke/991123 to your computer and use it in GitHub Desktop.
stream-twitter.js
var params = new Object();
var id;
var closeTimer;
var text = "";
var textOrig;
var entities;
var tweet;
var timeOut = 1000 * localStorage.getItem("timeout");
$(document).ready(function() {
paramsIn = window.location.href.split("?"); paramsIn = paramsIn[1].split("&") || null; for(var a in paramsIn) {
paramsIn[a] = paramsIn[a].split("="); params[paramsIn[a][0]] = unescape(paramsIn[a][1])}
id = params.id; try {
tweet = jQuery.parseJSON(chrome.extension.getBackgroundPage().response[id]); if(tweet.direct_message) {
if(tweet.direct_message.sender.id == localStorage.getItem("id")) {
prefix = "DM to " + tweet.direct_message.recipient.name + ": "; $("#reply").hide()}
else {
prefix = "DM: "}
if(localStorage.getItem("stickyDm") == "true") {
timeOut = 0}
$("#image").attr("src", tweet.direct_message.sender.profile_image_url); $("#title").text(tweet.direct_message.sender.name); $("#title").attr("href", "javascript:link('http://twitter.com/" + tweet.direct_message.sender.screen_name + "');"); $("#retweet, #favourite").hide(); text = prefix + tweet.direct_message.text}
else {
if(tweet.user.id == localStorage.getItem("id")) {
$("#retweet, #reply").hide()}
else {
$("#reply").attr("href", "javascript:reply(" + id + ")")}
$("#image").attr("src", tweet.user.profile_image_url); $("#title").text(tweet.user.name); $("#title").attr("href", "javascript:link('http://twitter.com/" + tweet.user.screen_name + "');"); textOrig = tweet.text; entities = tweet.entities.user_mentions; for(var a in tweet.entities.urls) {
entities[entities.length] = tweet.entities.urls[a]}
entities.sort(indices); if(entities.length > 0) {
for(var a in entities) {
item = entities[a]; if(a > 0) {
text += textOrig.substring(entities[a - 1].indices[1], item.indices[0])}
else {
if(item.indices[0] > 0) {
text = textOrig.substring(0, item.indices[0])}
}
if(item.screen_name) {
text += "@<a href = \"javascript:link('http://twitter.com/" + item.screen_name + "');\">" + item.screen_name + "</a>"}
if(item.url) {
text += "<a href = \"javascript:link('" + item.url + "');\">" + item.url + "</a>"}
}
text += textOrig.substr(entities[entities.length - 1].indices[1])}
if(!text) {
text = tweet.text}
}
$("#text").html(text); timer()}
catch(b) {
chrome.extension.getBackgroundPage().restart = true; window.close()}
$(window).mouseover(function() {
if(timeOut > 0) {
clearTimeout(closeTimer)}
}
); $(window).mouseout(function() {
if(timeOut > 0) {
closeTimer = setTimeout(function() {
window.close()}
, 2000)}
}
); $("#favourite").click(function() {
chrome.extension.getBackgroundPage().twitter.favourite(tweet.id_str); $("#favourite").css("background-image", "url('favourited.png')"); $("#favourite").unbind("click")}
); $("#retweet").click(function() {
chrome.extension.getBackgroundPage().twitter.retweet(tweet.id_str); $("#retweet").css("background-image", "url('retweeted.png')"); $("#retweet").unbind("click")}
)}
);
function link(a) {
chrome.tabs.create( {
url : a}
)}
function timer() {
if(timeOut > 0) {
closeTimer = setTimeout(function() {
window.close()}
, timeOut)}
}
function indices(d, c) {
return d.indices[0] - c.indices[0]}
function reply(a) {
chrome.windows.create( {
url : "reply.html?id=" + a, width : 500, height : 130, type : "popup"}
)};
/*
* Copyright 2008 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var OAuth;
if(OAuth == null) {
OAuth = {
}
}
OAuth.setProperties = function setProperties(a, c) {
if(a != null && c != null) {
for(var b in c) {
a[b] = c[b]}
}
return a};
OAuth.setProperties(OAuth, {
percentEncode : function percentEncode(b) {
if(b == null) {
return""}
if(b instanceof Array) {
var c = ""; for(var a = 0; a < b.length; ++b) {
if(c != "") {
c += "&"}
c += OAuth.percentEncode(b[a])}
return c}
b = encodeURIComponent(b); b = b.replace(/\!/g,"%21");b=b.replace(/\*/g,"%2A");b=b.replace(/\'/g,"%27");b=b.replace(/\(/g,"%28");b=b.replace(/\)/g,"%29");return b},decodePercent:function decodePercent(a){if(a!=null){a=a.replace(/\+/g," ")}return decodeURIComponent(a)},getParameterList:function getParameterList(a){if(a==null){return[]}if(typeof a!="object"){return OAuth.decodeForm(a+"")}if(a instanceof Array){return a}var b=[];for(var c in a){b.push([c,a[c]])}return b},getParameterMap:function getParameterMap(b){if(b==null){return{}}if(typeof b!="object"){return OAuth.getParameterMap(OAuth.decodeForm(b+""))}if(b instanceof Array){var d={};for(var c=0;c0){var d=a.indexOf("?");if(d<0){newURL+="?"}else{newURL+="&"}newURL+=b}}return newURL},getAuthorizationHeader:function getAuthorizationHeader(a,c){var h='OAuth realm="'+OAuth.percentEncode(a)+'"';var d=OAuth.getParameterList(c);for(var f=0;f OAuth.nonce.CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
OAuth.declareClass = function declareClass(d, a, c) {
var f = d[a];
d[a] = c;
if(c != null && f != null) {
for(var b in f) {
if(b != "prototype") {
c[b] = f[b]}
}
}
return c};
OAuth.declareClass(OAuth, "SignatureMethod", function OAuthSignatureMethod() {
}
);
OAuth.setProperties(OAuth.SignatureMethod.prototype, {
sign : function sign(c) {
var b = OAuth.SignatureMethod.getBaseString(c); var a = this.getSignature(b); OAuth.setParameter(c, "oauth_signature", a); return a}
, initialize : function initialize(c, a) {
var b; if(a.accessorSecret != null && c.length > 9 && c.substring(c.length - 9) == "-Accessor") {
b = a.accessorSecret}
else {
b = a.consumerSecret}
this.key = OAuth.percentEncode(b) + "&" + OAuth.percentEncode(a.tokenSecret)}
}
);
OAuth.setProperties(OAuth.SignatureMethod, {
sign : function sign(c, a) {
var b = OAuth.getParameterMap(c.parameters).oauth_signature_method; if(b == null || b == "") {
b = "HMAC-SHA1"; OAuth.setParameter(c, "oauth_signature_method", b)}
OAuth.SignatureMethod.newMethod(b, a).sign(c)}
, newMethod : function newMethod(d, a) {
var c = OAuth.SignatureMethod.REGISTERED[d]; if(c != null) {
var h = new c(); h.initialize(d, a); return h}
var g = new Error("signature_method_rejected"); var b = ""; for(var f in OAuth.SignatureMethod.REGISTERED) {
if(b != "") {
b += "&"}
b += OAuth.percentEncode(f)}
g.oauth_acceptable_signature_methods = b; throw g}
, REGISTERED : {
}
, registerMethodClass : function registerMethodClass(b, a) {
for(var c = 0; c < b.length; ++c) {
OAuth.SignatureMethod.REGISTERED[b[c]] = a}
}
, makeSubclass : function makeSubclass(a) {
var b = OAuth.SignatureMethod; var c = function() {
b.call(this)}; c.prototype = new b(); c.prototype.getSignature = a; c.prototype.constructor = c; return c}
, getBaseString : function getBaseString(g) {
var b = g.action; var h = b.indexOf("?"); var f; if(h < 0) {
f = g.parameters}
else {
f = OAuth.decodeForm(b.substring(h + 1)); var d = OAuth.getParameterList(g.parameters); for(var c = 0; c < d.length; ++c) {
f.push(d[c])}
}
return OAuth.percentEncode(g.method.toUpperCase()) + "&" + OAuth.percentEncode(OAuth.SignatureMethod.normalizeUrl(b)) + "&" + OAuth.percentEncode(OAuth.SignatureMethod.normalizeParameters(f))}
, normalizeUrl : function normalizeUrl(c) {
var d = OAuth.SignatureMethod.parseUri(c); var a = d.protocol.toLowerCase(); var g = d.authority.toLowerCase(); var h = (a == "http" && d.port == 80) || (a == "https" && d.port == 443); if(h) {
var b = g.lastIndexOf(":"); if(b >= 0) {
g = g.substring(0, b)}
}
var f = d.path; if(!f) {
f = "/"}
return a + "://" + g + f}
, parseUri : function parseUri(f) {
var d = {
key : ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], parser : {
strict :/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/}};var a=d.parser.strict.exec(f);var c={};var b=14;while(b--){c[d.key[b]]=a[b]||""}return c},normalizeParameters:function normalizeParameters(d){if(d==null){return""}var f=OAuth.getParameterList(d);var h=[];for(var g=0;gi[0]){return 1}return 0});var a=[];for(var c=0;c OAuth.SignatureMethod.registerMethodClass(["PLAINTEXT", "PLAINTEXT-Accessor"], OAuth.SignatureMethod.makeSubclass(function getSignature(a) {
return this.key}
));
OAuth.SignatureMethod.registerMethodClass(["HMAC-SHA1", "HMAC-SHA1-Accessor"], OAuth.SignatureMethod.makeSubclass(function getSignature(b) {
b64pad = "="; var a = b64_hmac_sha1(this.key, b); return a}
));
try {
OAuth.correctTimestampFromSrc()}
catch(e) {
};
var id;
var tweet;
var exit;
$(document).ready(function() {
jQuery.event.props.push("dataTransfer"); paramsIn = window.location.href.split("?"); params = []; if(paramsIn[1]) {
paramsIn = paramsIn[1].split("&") || null; for(var a in paramsIn) {
paramsIn[a] = paramsIn[a].split("="); params[paramsIn[a][0]] = unescape(paramsIn[a][1])}
}
if(params.id) {
id = params.id; try {
tweet = jQuery.parseJSON(chrome.extension.getBackgroundPage().response[id]); if(tweet.direct_message) {
document.title = "Reply to DM"}
else {
$("#text").text("@" + tweet.user.screen_name + " ")}
}
catch(b) {
alert("Sorry, an error has occurred. Please reply manually through twitter.com"); window.close(); chrome.extension.getBackgroundPage().location.reload()}
$("#text").selectRange($("#text").val().length, $("#text").val().length); $("#text").trigger("keyup")}
else {
$("#text").text(localStorage.getItem("TweetTemp")); $("#text").selectRange($("#text").val().length, $("#text").val().length); $("#text").trigger("keyup")}
$("#text").keyup(function() {
count = 140 - $("#text").val().length; $("#count").text(count); if(count < 0) {
$("#count").css("color", "#FF0000")}
else {
$("#count").css("color", "#333")}
if(!id) {
localStorage.setItem("TweetTemp", $("#text").val())}
}
); $("#send").click(function() {
text = $("#text").val(); if(text.length > 140) {
alert("Too many characters!")}
else {
if(id) {
if(tweet.direct_message) {
chrome.extension.getBackgroundPage().twitter.dm(text, tweet.direct_message.sender.id_str, tweet.direct_message.sender.screen_name)}
else {
chrome.extension.getBackgroundPage().twitter.update(text, tweet.id_str)}
exit = true; window.close()}
else {
chrome.extension.getBackgroundPage().twitter.update(text, null); chrome.tabs.getSelected(null, function(c) {
chrome.tabs.update(c.id, {
selected : true}
)}
)}
localStorage.removeItem("TweetTemp")}
}
); window.onbeforeunload = function() {
if(!exit) {
return("Discard tweet?")}
}
}
);
$.fn.selectRange = function(b, a) {
return this.each(function() {
if(this.setSelectionRange) {
this.focus(); this.setSelectionRange(b, a)}
else {
if(this.createTextRange) {
var c = this.createTextRange(); c.collapse(true); c.moveEnd("character", a); c.moveStart("character", b); c.select()}
}
}
)};
var twitter = {
};
var response;
var restart = false;
twitter.version = 2;
twitter.consumerKey = "JPRtaafuUN3zcqFjxXCbJQ";
twitter.consumerSecret = "VOT7yrQ5AZ57QzqljTRRjwylf5KPUfWoUujibZMEw";
temp = localStorage.getItem("requestToken");
if(temp) {
twitter.requestToken = temp}
temp = localStorage.getItem("requestTokenSecret");
if(temp) {
twitter.requestTokenSecret = temp}
temp = localStorage.getItem("accessToken");
if(temp) {
twitter.accessToken = temp}
temp = localStorage.getItem("accessTokenSecret");
if(temp) {
twitter.accessTokenSecret = temp}
var logoutItems = ["accessToken", "accessTokenSecret", "screenName", "id", "image", "name"];
twitter.setup = function() {
if(!twitter.accessToken ||!twitter.accessTokenSecret) {
params = window.location.href.split("?");
if(params[1]) {
params = params[1].split("&") || null;
for(var b in params) {
params[b] = params[b].split("=");
if(params[b][0] == "oauth_verifier") {
var a = params[b][1]}
}
}
if(!twitter.requestToken ||!twitter.requestTokenSecret ||!a) {
twitter.oauthRequest( {
url : "https://api.twitter.com/oauth/request_token", type : "text", method : "POST", token : true, tokenSecret : true}
, [["oauth_callback", escape(window.top.location)]], function(c) {
c = c.split("&"); dataArray = new Array(); for(b in c) {
dataTemp = c[b].split("="); dataArray[dataTemp[0]] = dataTemp[1]}
localStorage.setItem("requestToken", dataArray.oauth_token); localStorage.setItem("requestTokenSecret", dataArray.oauth_token_secret); if(dataArray.oauth_token) {
chrome.tabs.create( {
url : "https://api.twitter.com/oauth/authorize?oauth_token=" + dataArray.oauth_token}
)}
else {
setTimeout(function() {
alert("An error occurred! Twitter Notifier will try again.")}
, 5000)}
}
)}
else {
twitter.oauthRequest( {
url : "https://api.twitter.com/oauth/access_token", type : "text", method : "POST", token : twitter.requestToken, tokenSecret : twitter.requestTokenSecret}
, [["oauth_verifier", a]], function(c) {
c = c.split("&"); dataArray = new Array(); for(b in c) {
dataTemp = c[b].split("="); dataArray[dataTemp[0]] = dataTemp[1]}
localStorage.setItem("accessToken", dataArray.oauth_token); localStorage.setItem("accessTokenSecret", dataArray.oauth_token_secret); localStorage.removeItem("requestToken"); localStorage.removeItem("requestTokenSecret"); twitter.accessToken = dataArray.oauth_token; twitter.accessTokenSecret = dataArray.oauth_token_secret; chrome.extension.getBackgroundPage().location.reload(); webkitNotifications.createNotification("48.png", "Authorised!", "Twitter Notifier is now authorised and running.").show(); chrome.tabs.getCurrent(function(d) {
chrome.tabs.remove(d.id)}
)}
)}
}
else {
twitter.oauthRequest( {
url : "https://api.twitter.com/1/account/verify_credentials.json"}
, [], function(c) {
localStorage.setItem("id", c.id); localStorage.setItem("name", c.name); localStorage.setItem("screenName", c.screen_name); localStorage.setItem("image", c.profile_image_url)}
);
twitter.stream()}
};
twitter.oauthRequest = function(c, b, d, a) {
if(!c.token) {
c.token = twitter.accessToken}
if(!c.tokenSecret) {
c.tokenSecret = twitter.accessTokenSecret}
if(!c.type) {
c.type = "json"}
if(!c.method) {
c.method = "GET"}
accessor = {
consumerSecret : twitter.consumerSecret, };
message = {
action : c.url, method : c.method, parameters : [["oauth_consumer_key", twitter.consumerKey], ["oauth_signature_method", "HMAC-SHA1"], ["oauth_version", "1.0"]]};
if(c.token != true) {
message.parameters.push(["oauth_token", c.token])}
if(c.tokenSecret != true) {
accessor.tokenSecret = c.tokenSecret}
for(i in b) {
if(b[i][0] == "oauth_callback") {
b[i][1] = unescape(b[i][1])}
message.parameters.push(b[i])}
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
if(b && b[0] == "stream") {
$.ajax( {
url : message.action, type : message.method, data : OAuth.getParameterMap(message.parameters), dataType : c.type, beforeSend : function(g) {
var g; var f = 0; var e; var h; setInterval(function() {
response = g.responseText.split("\r"); h++; if(h > 45 || response.length > 500 || restart) {
g.abort()}
if(response.length > f + 1) {
if(!response[f]) {
g.abort()}
if(response[f].length > 1) {
if(data = jQuery.parseJSON(response[f])) {
if(data.text && (localStorage.getItem("notifyTweet") == "true" || localStorage.getItem("notifyMention") == "true")) {
e = false; if(data.entities.user_mentions) {
for(var j in data.entities.user_mentions) {
if(data.entities.user_mentions[j].screen_name == localStorage.getItem("screenName")) {
e = true}
}
}
if(localStorage.getItem("notifyTweet") == "true" || (localStorage.getItem("notifyMention") == "true" && e == true)) {
webkitNotifications.createHTMLNotification("notification.html?id=" + f).show()}
}
if(data.direct_message && localStorage.getItem("notifyDm") == "true") {
webkitNotifications.createHTMLNotification("notification.html?id=" + f).show()}
}
else {
restart = true}
}
f++; h = 0}
}
, 1000)}
, complete : function(e, f) {
streamError(e.status)}
}
)}
else {
$.ajax( {
url : message.action, type : message.method, data : OAuth.getParameterMap(message.parameters), dataType : c.type, success : function(f, e, g) {
d(f)}
, error : function(f, e, g) {
console.log(f.responseText); a(f.responseText, b)}
}
)}
};
twitter.stream = function() {
twitter.oauthRequest( {
url : "https://userstream.twitter.com/2/user.json"}
, ["stream"], function(a) {
}
)};
var wait = 0;
var waitReset;
function streamError(a) {
if(a > 200) {
if(wait == 0) {
wait = 5000}
if(wait < 240000) {
wait = wait * 2}
else {
notif = webkitNotifications.createNotification("48.png", "Twitter Error", "Twitter Notifier couldn't connect to Twitter - maybe Twitter's down, or maybe you aren't logged in properly. Go to the options page to logout and in again.");
notif.show();
setTimeout(function() {
document.location.reload()}
, 10000)}
setTimeout(twitter.stream, wait)}
else {
if(wait < 4000) {
wait += 250}
else {
document.location.reload()}
setTimeout(twitter.stream, wait)}
waitReset = setTimeout(function() {
wait = 0}
, 60000)}
twitter.favourite = function(a) {
twitter.oauthRequest( {
method : "POST", url : "https://api.twitter.com/1/favorites/create/" + a + ".json"}
, [], function() {
}
, function(b) {
b = jQuery.parseJSON(b); webkitNotifications.createNotification("error.png", "Could not favourite", "Error: " + b.error).show()}
)};
twitter.retweet = function(a) {
twitter.oauthRequest( {
method : "POST", url : "https://api.twitter.com/1/statuses/retweet/" + a + ".json"}
, [], function() {
}
, function(b) {
b = jQuery.parseJSON(b); webkitNotifications.createNotification("error.png", "Retweet failed", "Error: " + b.error).show()}
)};
twitter.update = function(a, b) {
p = [["status", a]];
if(b) {
p.push(["in_reply_to_status_id", b])}
twitter.oauthRequest( {
method : "POST", url : "https://api.twitter.com/1/statuses/update.json"}
, p, function() {
}
, function(c, e) {
c = jQuery.parseJSON(c); console.log(c); webkitNotifications.createNotification("error.png", "Status could not be sent", "Error: " + c.error).show(); for(var d in e) {
if(e[d][0] == "status") {
e = e[d][1]}
}
chrome.tabs.create( {
url : "http://twitter.com/?status=" + e}
)}
)};
twitter.dm = function(b, c, a) {
twitter.oauthRequest( {
method : "POST", url : "https://api.twitter.com/1/direct_messages/new.json"}
, [["text", b], ["user_id", c], ["screen_name", a]], function() {
}
, function(d) {
d = jQuery.parseJSON(d); webkitNotifications.createNotification("error.png", "DM Could not be sent", "Error: " + d.error).show()}
)};
twitter.logout = function() {
for(var a in logoutItems) {
localStorage.removeItem(logoutItems[a])}
chrome.extension.getBackgroundPage().location.reload()};
if(!localStorage.getItem("version") || localStorage.getItem("version") < twitter.version) {
if(!localStorage.getItem("stickyDm")) {
localStorage.setItem("stickyDm", "true");
localStorage.setItem("notifyDm", "true");
localStorage.setItem("notifyTweet", "true");
localStorage.setItem("notifyMention", "true");
localStorage.setItem("timeout", "10")}
versionTemp = localStorage.getItem("version");
localStorage.setItem("version", twitter.version);
webkitNotifications.createHTMLNotification("updated.html").show();
if(versionTemp < 1.03) {
twitter.logout()}
else {
twitter.setup()}
}
else {
twitter.setup()};
Close Window
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment