converse.js 149 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300
  1. /*!
  2. * Converse.js (Web-based XMPP instant messaging client)
  3. * http://conversejs.org
  4. *
  5. * Copyright (c) 2012, Jan-Carel Brand <jc@opkode.com>
  6. * Dual licensed under the MIT and GPL Licenses
  7. */
  8. // AMD/global registrations
  9. (function (root, factory) {
  10. if (typeof console === "undefined" || typeof console.log === "undefined") {
  11. console = { log: function () {}, error: function () {} };
  12. }
  13. if (typeof define === 'function' && define.amd) {
  14. define("converse", [
  15. "otr",
  16. "crypto.aes",
  17. "locales",
  18. "backbone.localStorage",
  19. "jquery.tinysort",
  20. "strophe",
  21. "strophe.muc",
  22. "strophe.roster",
  23. "strophe.vcard",
  24. "strophe.disco"
  25. ], function(otr, crypto) {
  26. // Use Mustache style syntax for variable interpolation
  27. _.templateSettings = {
  28. evaluate : /\{\[([\s\S]+?)\]\}/g,
  29. interpolate : /\{\{([\s\S]+?)\}\}/g
  30. };
  31. return factory(jQuery, _, crypto, otr, console);
  32. }
  33. );
  34. } else {
  35. // Browser globals
  36. _.templateSettings = {
  37. evaluate : /\{\[([\s\S]+?)\]\}/g,
  38. interpolate : /\{\{([\s\S]+?)\}\}/g
  39. };
  40. root.converse = factory(jQuery, _, crypto, otr, console || {log: function(){}});
  41. }
  42. }(this, function ($, _, crypto, otr, console) {
  43. var converse = {};
  44. converse.initialize = function (settings, callback) {
  45. var converse = this;
  46. // Constants
  47. // ---------
  48. var UNENCRYPTED = 0;
  49. var UNVERIFIED= 1;
  50. var VERIFIED= 2;
  51. var FINISHED = 3;
  52. var KEY = {
  53. ENTER: 13
  54. };
  55. // Default configuration values
  56. // ----------------------------
  57. this.allow_contact_requests = true;
  58. this.allow_muc = true;
  59. this.allow_otr = true;
  60. this.animate = true;
  61. this.auto_list_rooms = false;
  62. this.auto_subscribe = false;
  63. this.bosh_service_url = undefined; // The BOSH connection manager URL.
  64. this.debug = false;
  65. this.hide_muc_server = false;
  66. this.i18n = locales.en;
  67. this.prebind = false;
  68. this.show_controlbox_by_default = false;
  69. this.show_only_online_users = false;
  70. this.show_emoticons = true;
  71. this.show_toolbar = true;
  72. this.testing = false; // Exposes sensitive data for testing. Never set to true in production systems!
  73. this.xhr_custom_status = false;
  74. this.xhr_user_search = false;
  75. // Allow only whitelisted configuration attributes to be overwritten
  76. _.extend(this, _.pick(settings, [
  77. 'allow_contact_requests',
  78. 'allow_muc',
  79. 'allow_otr',
  80. 'animate',
  81. 'auto_list_rooms',
  82. 'auto_subscribe',
  83. 'bosh_service_url',
  84. 'connection',
  85. 'debug',
  86. 'fullname',
  87. 'hide_muc_server',
  88. 'i18n',
  89. 'jid',
  90. 'prebind',
  91. 'rid',
  92. 'show_controlbox_by_default',
  93. 'show_emoticons',
  94. 'show_only_online_users',
  95. 'show_toolbar',
  96. 'sid',
  97. 'testing',
  98. 'xhr_custom_status',
  99. 'xhr_user_search'
  100. ]));
  101. // Translation machinery
  102. // ---------------------
  103. var __ = $.proxy(function (str) {
  104. // Translation factory
  105. if (this.i18n === undefined) {
  106. this.i18n = locales.en;
  107. }
  108. var t = this.i18n.translate(str);
  109. if (arguments.length>1) {
  110. return t.fetch.apply(t, [].slice.call(arguments,1));
  111. } else {
  112. return t.fetch();
  113. }
  114. }, this);
  115. var ___ = function (str) {
  116. /* XXX: This is part of a hack to get gettext to scan strings to be
  117. * translated. Strings we cannot send to the function above because
  118. * they require variable interpolation and we don't yet have the
  119. * variables at scan time.
  120. *
  121. * See actionInfoMessages
  122. */
  123. return str;
  124. };
  125. // Translation aware constants
  126. // ---------------------------
  127. var OTR_CLASS_MAPPING = {};
  128. OTR_CLASS_MAPPING[UNENCRYPTED] = 'unencrypted';
  129. OTR_CLASS_MAPPING[UNVERIFIED] = 'unverified';
  130. OTR_CLASS_MAPPING[VERIFIED] = 'verified';
  131. OTR_CLASS_MAPPING[FINISHED] = 'finished';
  132. var OTR_TRANSLATED_MAPPING = {};
  133. OTR_TRANSLATED_MAPPING[UNENCRYPTED] = __('unencrypted');
  134. OTR_TRANSLATED_MAPPING[UNVERIFIED] = __('unverified');
  135. OTR_TRANSLATED_MAPPING[VERIFIED] = __('verified');
  136. OTR_TRANSLATED_MAPPING[FINISHED] = __('finished');
  137. var STATUSES = {
  138. 'dnd': __('This contact is busy'),
  139. 'online': __('This contact is online'),
  140. 'offline': __('This contact is offline'),
  141. 'unavailable': __('This contact is unavailable'),
  142. 'xa': __('This contact is away for an extended period'),
  143. 'away': __('This contact is away')
  144. };
  145. // Module-level variables
  146. // ----------------------
  147. this.callback = callback || function () {};
  148. this.initial_presence_sent = 0;
  149. this.msg_counter = 0;
  150. // Module-level functions
  151. // ----------------------
  152. this.autoLink = function (text) {
  153. // Convert URLs into hyperlinks
  154. var re = /((http|https|ftp):\/\/[\w?=&.\/\-;#~%\-]+(?![\w\s?&.\/;#~%"=\-]*>))/g;
  155. return text.replace(re, '<a target="_blank" href="$1">$1</a>');
  156. };
  157. this.giveFeedback = function (message, klass) {
  158. $('.conn-feedback').text(message);
  159. $('.conn-feedback').attr('class', 'conn-feedback');
  160. if (klass) {
  161. $('.conn-feedback').addClass(klass);
  162. }
  163. };
  164. this.log = function (txt, level) {
  165. if (this.debug) {
  166. if (level == 'error') {
  167. console.log('ERROR: '+txt);
  168. } else {
  169. console.log(txt);
  170. }
  171. }
  172. };
  173. this.getVCard = function (jid, callback, errback) {
  174. converse.connection.vcard.get(
  175. $.proxy(function (iq) {
  176. // Successful callback
  177. $vcard = $(iq).find('vCard');
  178. var fullname = $vcard.find('FN').text(),
  179. img = $vcard.find('BINVAL').text(),
  180. img_type = $vcard.find('TYPE').text(),
  181. url = $vcard.find('URL').text();
  182. if (jid) {
  183. var rosteritem = converse.roster.get(jid);
  184. if (rosteritem) {
  185. rosteritem.save({
  186. 'fullname': fullname || jid,
  187. 'image_type': img_type,
  188. 'image': img,
  189. 'url': url,
  190. 'vcard_updated': converse.toISOString(new Date())
  191. });
  192. }
  193. }
  194. if (callback) {
  195. callback(jid, fullname, img, img_type, url);
  196. }
  197. }, this),
  198. jid,
  199. function (iq) {
  200. // Error callback
  201. var rosteritem = converse.roster.get(jid);
  202. if (rosteritem) {
  203. rosteritem.save({
  204. 'vcard_updated': converse.toISOString(new Date())
  205. });
  206. }
  207. if (errback) {
  208. errback(iq);
  209. }
  210. });
  211. };
  212. this.onConnect = function (status) {
  213. var $button, $form;
  214. if (status === Strophe.Status.CONNECTED) {
  215. converse.log('Connected');
  216. converse.onConnected();
  217. } else if (status === Strophe.Status.DISCONNECTED) {
  218. $form = $('#converse-login');
  219. $button = $form.find('input[type=submit]');
  220. if ($button) { $button.show().siblings('span').remove(); }
  221. converse.giveFeedback(__('Disconnected'), 'error');
  222. converse.connection.connect(
  223. converse.connection.jid,
  224. converse.connection.pass,
  225. converse.onConnect
  226. );
  227. } else if (status === Strophe.Status.Error) {
  228. $form = $('#converse-login');
  229. $button = $form.find('input[type=submit]');
  230. if ($button) { $button.show().siblings('span').remove(); }
  231. converse.giveFeedback(__('Error'), 'error');
  232. } else if (status === Strophe.Status.CONNECTING) {
  233. converse.giveFeedback(__('Connecting'));
  234. } else if (status === Strophe.Status.CONNFAIL) {
  235. converse.chatboxesview.views.controlbox.trigger('connection-fail');
  236. converse.giveFeedback(__('Connection Failed'), 'error');
  237. } else if (status === Strophe.Status.AUTHENTICATING) {
  238. converse.giveFeedback(__('Authenticating'));
  239. } else if (status === Strophe.Status.AUTHFAIL) {
  240. converse.chatboxesview.views.controlbox.trigger('auth-fail');
  241. converse.giveFeedback(__('Authentication Failed'), 'error');
  242. } else if (status === Strophe.Status.DISCONNECTING) {
  243. converse.giveFeedback(__('Disconnecting'), 'error');
  244. } else if (status === Strophe.Status.ATTACHED) {
  245. converse.log('Attached');
  246. converse.onConnected();
  247. }
  248. };
  249. this.toISOString = function (date) {
  250. var pad;
  251. if (typeof date.toISOString !== 'undefined') {
  252. return date.toISOString();
  253. } else {
  254. // IE <= 8 Doesn't have toISOStringMethod
  255. pad = function (num) {
  256. return (num < 10) ? '0' + num : '' + num;
  257. };
  258. return date.getUTCFullYear() + '-' +
  259. pad(date.getUTCMonth() + 1) + '-' +
  260. pad(date.getUTCDate()) + 'T' +
  261. pad(date.getUTCHours()) + ':' +
  262. pad(date.getUTCMinutes()) + ':' +
  263. pad(date.getUTCSeconds()) + '.000Z';
  264. }
  265. };
  266. this.parseISO8601 = function (datestr) {
  267. /* Parses string formatted as 2013-02-14T11:27:08.268Z to a Date obj.
  268. */
  269.     var numericKeys = [1, 4, 5, 6, 7, 10, 11],
  270. struct = /^\s*(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}\.?\d*)Z\s*$/.exec(datestr),
  271. minutesOffset = 0,
  272. i, k;
  273. for (i = 0; (k = numericKeys[i]); ++i) {
  274. struct[k] = +struct[k] || 0;
  275. }
  276. // allow undefined days and months
  277. struct[2] = (+struct[2] || 1) - 1;
  278. struct[3] = +struct[3] || 1;
  279. if (struct[8] !== 'Z' && struct[9] !== undefined) {
  280. minutesOffset = struct[10] * 60 + struct[11];
  281. if (struct[9] === '+') {
  282. minutesOffset = 0 - minutesOffset;
  283. }
  284. }
  285. return new Date(Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]));
  286. };
  287. this.updateMsgCounter = function () {
  288. if (this.msg_counter > 0) {
  289. if (document.title.search(/^Messages \(\d+\) /) == -1) {
  290. document.title = "Messages (" + this.msg_counter + ") " + document.title;
  291. } else {
  292. document.title = document.title.replace(/^Messages \(\d+\) /, "Messages (" + this.msg_counter + ") ");
  293. }
  294. window.blur();
  295. window.focus();
  296. } else if (document.title.search(/^Messages \(\d+\) /) != -1) {
  297. document.title = document.title.replace(/^Messages \(\d+\) /, "");
  298. }
  299. };
  300. this.incrementMsgCounter = function () {
  301. this.msg_counter += 1;
  302. this.updateMsgCounter();
  303. };
  304. this.clearMsgCounter = function () {
  305. this.msg_counter = 0;
  306. this.updateMsgCounter();
  307. };
  308. this.showControlBox = function () {
  309. var controlbox = this.chatboxes.get('controlbox');
  310. if (!controlbox) {
  311. this.chatboxes.add({
  312. id: 'controlbox',
  313. box_id: 'controlbox',
  314. visible: true
  315. });
  316. if (this.connection) {
  317. this.chatboxes.get('controlbox').save();
  318. }
  319. } else {
  320. controlbox.trigger('show');
  321. }
  322. };
  323. this.toggleControlBox = function () {
  324. if ($("div#controlbox").is(':visible')) {
  325. var controlbox = this.chatboxes.get('controlbox');
  326. if (this.connection) {
  327. controlbox.destroy();
  328. } else {
  329. controlbox.trigger('hide');
  330. }
  331. } else {
  332. this.showControlBox();
  333. }
  334. };
  335. this.initStatus = function (callback) {
  336. this.xmppstatus = new this.XMPPStatus();
  337. var id = hex_sha1('converse.xmppstatus-'+this.bare_jid);
  338. this.xmppstatus.id = id; // This appears to be necessary for backbone.localStorage
  339. this.xmppstatus.localStorage = new Backbone.LocalStorage(id);
  340. this.xmppstatus.fetch({success: callback, error: callback});
  341. };
  342. this.initRoster = function () {
  343. // Set up the roster
  344. this.roster = new this.RosterItems();
  345. this.roster.localStorage = new Backbone.LocalStorage(
  346. hex_sha1('converse.rosteritems-'+converse.bare_jid));
  347. // Register callbacks that depend on the roster
  348. this.connection.roster.registerCallback(
  349. $.proxy(this.roster.rosterHandler, this.roster),
  350. null, 'presence', null);
  351. this.connection.addHandler(
  352. $.proxy(this.roster.subscribeToSuggestedItems, this.roster),
  353. 'http://jabber.org/protocol/rosterx', 'message', null);
  354. this.connection.addHandler(
  355. $.proxy(function (presence) {
  356. this.presenceHandler(presence);
  357. return true;
  358. }, this.roster), null, 'presence', null);
  359. // No create the view which will fetch roster items from
  360. // localStorage
  361. this.rosterview = new this.RosterView({'model':this.roster});
  362. };
  363. this.onConnected = function () {
  364. if (this.debug) {
  365. this.connection.xmlInput = function (body) { console.log(body); };
  366. this.connection.xmlOutput = function (body) { console.log(body); };
  367. Strophe.log = function (level, msg) { console.log(level+' '+msg); };
  368. Strophe.error = function (msg) { console.log('ERROR: '+msg); };
  369. }
  370. this.bare_jid = Strophe.getBareJidFromJid(this.connection.jid);
  371. this.domain = Strophe.getDomainFromJid(this.connection.jid);
  372. this.features = new this.Features();
  373. this.initStatus($.proxy(function () {
  374. this.initRoster();
  375. this.chatboxes.onConnected();
  376. this.connection.roster.get(function () {});
  377. $(document).click(function() {
  378. if ($('.toggle-otr ul').is(':visible')) {
  379. $('.toggle-otr ul', this).slideUp();
  380. }
  381. if ($('.toggle-smiley ul').is(':visible')) {
  382. $('.toggle-smiley ul', this).slideUp();
  383. }
  384. });
  385. $(window).on("blur focus", $.proxy(function(e) {
  386. if ((this.windowState != e.type) && (e.type == 'focus')) {
  387. converse.clearMsgCounter();
  388. }
  389. this.windowState = e.type;
  390. },this));
  391. this.giveFeedback(__('Online Contacts'));
  392. if (this.testing) {
  393. this.callback(this);
  394. } else {
  395. this.callback();
  396. }
  397. }, this));
  398. };
  399. // Backbone Models and Views
  400. // -------------------------
  401. this.Message = Backbone.Model.extend();
  402. this.Messages = Backbone.Collection.extend({
  403. model: converse.Message
  404. });
  405. this.ChatBox = Backbone.Model.extend({
  406. initialize: function () {
  407. if (this.get('box_id') !== 'controlbox') {
  408. if (_.contains([UNVERIFIED, VERIFIED], this.get('otr_status'))) {
  409. this.initiateOTR();
  410. }
  411. this.messages = new converse.Messages();
  412. this.messages.localStorage = new Backbone.LocalStorage(
  413. hex_sha1('converse.messages'+this.get('jid')+converse.bare_jid));
  414. this.set({
  415. 'user_id' : Strophe.getNodeFromJid(this.get('jid')),
  416. 'box_id' : hex_sha1(this.get('jid')),
  417. 'otr_status': this.get('otr_status') || UNENCRYPTED
  418. });
  419. }
  420. },
  421. getSession: function () {
  422. // XXX: sessionStorage is not supported in IE < 8. Perhaps a
  423. // user alert is required here...
  424. var saved_key = window.sessionStorage[hex_sha1(this.id+'priv_key')];
  425. var instance_tag = window.sessionStorage[hex_sha1(this.id+'instance_tag')];
  426. var cipher = crypto.lib.PasswordBasedCipher;
  427. var pass = converse.connection.pass;
  428. var result, key;
  429. if (saved_key && instance_tag) {
  430. var decrypted = cipher.decrypt(crypto.algo.AES, saved_key, pass);
  431. key = otr.DSA.parsePrivate(decrypted.toString(crypto.enc.Latin1));
  432. if (cipher.decrypt(crypto.algo.AES, this.get('pass_check'), pass).toString(crypto.enc.Latin1) === 'match') {
  433. // Verified that the user's password is still the same
  434. this.trigger('showHelpMessages', [__('Re-establishing encrypted session')]);
  435. return {
  436. 'key': key,
  437. 'instance_tag': instance_tag
  438. };
  439. }
  440. }
  441. // We need to generate a new key and instance tag
  442. result = alert(__('Your browser needs to generate a private key, which will be used in your encrypted chat session. This can take up to 30 seconds during which your browser might freeze and become unresponsive.'));
  443. instance_tag = otr.OTR.makeInstanceTag();
  444. key = new otr.DSA();
  445. // Encrypt the key and set in sessionStorage. Also store
  446. // instance tag
  447. window.sessionStorage[hex_sha1(this.id+'priv_key')] =
  448. cipher.encrypt(crypto.algo.AES, key.packPrivate(), pass).toString();
  449. window.sessionStorage[hex_sha1(this.id+'instance_tag')] = instance_tag;
  450. this.trigger('showHelpMessages', [__('Private key generated.')]);
  451. this.save({'pass_check': cipher.encrypt(crypto.algo.AES, 'match', pass).toString()});
  452. return {
  453. 'key': key,
  454. 'instance_tag': instance_tag
  455. };
  456. },
  457. updateOTRStatus: function (state) {
  458. switch (state) {
  459. case otr.OTR.CONST.STATUS_AKE_SUCCESS:
  460. if (this.otr.msgstate === otr.OTR.CONST.MSGSTATE_ENCRYPTED) {
  461. this.save({'otr_status': UNVERIFIED});
  462. }
  463. break;
  464. case otr.OTR.CONST.STATUS_END_OTR:
  465. if (this.otr.msgstate === otr.OTR.CONST.MSGSTATE_FINISHED) {
  466. this.save({'otr_status': FINISHED});
  467. } else if (this.otr.msgstate === otr.OTR.CONST.MSGSTATE_PLAINTEXT) {
  468. this.save({'otr_status': UNENCRYPTED});
  469. }
  470. break;
  471. }
  472. },
  473. onSMP: function (type, data) {
  474. // Event handler for SMP (Socialist's Millionaire Protocol)
  475. // used by OTR (off-the-record).
  476. switch (type) {
  477. case 'question':
  478. this.otr.smpSecret(prompt(__(
  479. 'Authentication request from %1$s\n\nYour buddy is attempting to verify your identity, by asking you the question below.\n\n%2$s',
  480. [this.get('fullname'), data])));
  481. break;
  482. case 'trust':
  483. if (this.otr.trust === true) {
  484. this.save({'otr_status': VERIFIED});
  485. } else {
  486. this.trigger(
  487. 'showHelpMessages',
  488. [__("Could not verify this user's identify.")],
  489. 'error');
  490. this.save({'otr_status': UNVERIFIED});
  491. }
  492. break;
  493. default:
  494. throw new Error('Unknown type.');
  495. }
  496. },
  497. initiateOTR: function (query_msg) {
  498. // Sets up an OTR object through which we can send and receive
  499. // encrypted messages.
  500. //
  501. // If 'query_msg' is passed in, it means there is an alread incoming
  502. // query message from our buddy. Otherwise, it is us who will
  503. // send the query message to them.
  504. this.save({'otr_status': UNENCRYPTED});
  505. session = this.getSession();
  506. this.otr = new otr.OTR({
  507. fragment_size: 140,
  508. send_interval: 200,
  509. priv: session.key,
  510. instance_tag: session.instance_tag,
  511. debug: this.debug
  512. });
  513. this.otr.on('status', $.proxy(this.updateOTRStatus, this));
  514. this.otr.on('smp', $.proxy(this.onSMP, this));
  515. this.otr.on('ui', $.proxy(function (msg) {
  516. this.trigger('showReceivedOTRMessage', msg);
  517. }, this));
  518. this.otr.on('io', $.proxy(function (msg) {
  519. this.trigger('sendMessageStanza', msg);
  520. }, this));
  521. this.otr.on('error', $.proxy(function (msg) {
  522. this.trigger('showOTRError', msg);
  523. }, this));
  524. if (query_msg) {
  525. this.otr.receiveMsg(query_msg);
  526. } else {
  527. this.otr.sendQueryMsg();
  528. }
  529. },
  530. endOTR: function () {
  531. if (this.otr) {
  532. this.otr.endOtr();
  533. }
  534. this.save({'otr_status': UNENCRYPTED});
  535. },
  536. createMessage: function (message) {
  537. var $message = $(message),
  538. body = converse.autoLink($message.children('body').text()),
  539. from = Strophe.getBareJidFromJid($message.attr('from')),
  540. composing = $message.find('composing'),
  541. delayed = $message.find('delay').length > 0,
  542. fullname = (this.get('fullname')||'').split(' ')[0],
  543. stamp, time, sender;
  544. if (!body) {
  545. if (composing.length) {
  546. this.messages.add({
  547. fullname: fullname,
  548. sender: 'them',
  549. delayed: delayed,
  550. time: converse.toISOString(new Date()),
  551. composing: composing.length
  552. });
  553. }
  554. } else {
  555. if (delayed) {
  556. stamp = $message.find('delay').attr('stamp');
  557. time = stamp;
  558. } else {
  559. time = converse.toISOString(new Date());
  560. }
  561. if (from == converse.bare_jid) {
  562. sender = 'me';
  563. } else {
  564. sender = 'them';
  565. }
  566. this.messages.create({
  567. fullname: fullname,
  568. sender: sender,
  569. delayed: delayed,
  570. time: time,
  571. message: body
  572. });
  573. }
  574. },
  575. messageReceived: function (message) {
  576. var $body = $(message).children('body');
  577. var text = ($body.length > 0 ? converse.autoLink($body.text()) : undefined);
  578. if ((!text) || (!converse.allow_otr)) {
  579. return this.createMessage(message);
  580. }
  581. if (_.contains([UNVERIFIED, VERIFIED], this.get('otr_status'))) {
  582. this.otr.receiveMsg(text);
  583. } else {
  584. if (text.match(/^\?OTR/)) {
  585. // They want to initiate OTR
  586. if (!this.otr) {
  587. this.initiateOTR(text);
  588. } else {
  589. this.otr.receiveMsg(text);
  590. }
  591. } else {
  592. // Normal unencrypted message.
  593. this.createMessage(message);
  594. }
  595. }
  596. }
  597. });
  598. this.ChatBoxView = Backbone.View.extend({
  599. length: 200,
  600. tagName: 'div',
  601. className: 'chatbox',
  602. events: {
  603. 'click .close-chatbox-button': 'closeChat',
  604. 'keypress textarea.chat-textarea': 'keyPressed',
  605. 'click .toggle-smiley': 'toggleSmileyMenu',
  606. 'click .toggle-smiley ul li': 'insertSmiley',
  607. 'click .toggle-otr': 'toggleOTRMenu',
  608. 'click .start-otr': 'startOTRFromToolbar',
  609. 'click .end-otr': 'endOTR',
  610. 'click .auth-otr': 'authOTR'
  611. },
  612. template: _.template(
  613. '<div class="chat-head chat-head-chatbox">' +
  614. '<a class="close-chatbox-button icon-close"></a>' +
  615. '<a href="{{url}}" target="_blank" class="user">' +
  616. '<div class="chat-title"> {{ fullname }} </div>' +
  617. '</a>' +
  618. '<p class="user-custom-message"><p/>' +
  619. '</div>' +
  620. '<div class="chat-content"></div>' +
  621. '<form class="sendXMPPMessage" action="" method="post">' +
  622. '{[ if ('+converse.show_toolbar+') { ]}' +
  623. '<ul class="chat-toolbar no-text-select"></ul>'+
  624. '{[ } ]}' +
  625. '<textarea ' +
  626. 'type="text" ' +
  627. 'class="chat-textarea" ' +
  628. 'placeholder="'+__('Personal message')+'"/>'+
  629. '</form>'
  630. ),
  631. toolbar_template: _.template(
  632. '{[ if (show_emoticons) { ]}' +
  633. '<li class="toggle-smiley icon-happy" title="Insert a smilery">' +
  634. '<ul>' +
  635. '<li><a class="icon-smiley" href="#" data-emoticon=":)"></a></li>'+
  636. '<li><a class="icon-wink" href="#" data-emoticon=";)"></a></li>'+
  637. '<li><a class="icon-grin" href="#" data-emoticon=":D"></a></li>'+
  638. '<li><a class="icon-tongue" href="#" data-emoticon=":P"></a></li>'+
  639. '<li><a class="icon-cool" href="#" data-emoticon="8)"></a></li>'+
  640. '<li><a class="icon-evil" href="#" data-emoticon=">:)"></a></li>'+
  641. '<li><a class="icon-confused" href="#" data-emoticon=":S"></a></li>'+
  642. '<li><a class="icon-wondering" href="#" data-emoticon=":\"></a></li>'+
  643. '<li><a class="icon-angry" href="#" data-emoticon=">:("></a></li>'+
  644. '<li><a class="icon-sad" href="#" data-emoticon=":("></a></li>'+
  645. '<li><a class="icon-shocked" href="#" data-emoticon=":O"></a></li>'+
  646. '<li><a class="icon-thumbs-up" href="#" data-emoticon="(^.^)b"></a></li>'+
  647. '<li><a class="icon-heart" href="#" data-emoticon="<3"></a></li>'+
  648. '</ul>' +
  649. '</li>' +
  650. '{[ } ]}' +
  651. '{[ if (allow_otr) { ]}' +
  652. '<li class="toggle-otr {{otr_status_class}}" title="{{otr_tooltip}}">'+
  653. '<span class="chat-toolbar-text">{{otr_translated_status}}</span>'+
  654. '{[ if (otr_status == "'+UNENCRYPTED+'") { ]}' +
  655. '<span class="icon-unlocked"></span>'+
  656. '{[ } ]}' +
  657. '{[ if (otr_status == "'+UNVERIFIED+'") { ]}' +
  658. '<span class="icon-lock"></span>'+
  659. '{[ } ]}' +
  660. '{[ if (otr_status == "'+VERIFIED+'") { ]}' +
  661. '<span class="icon-lock"></span>'+
  662. '{[ } ]}' +
  663. '{[ if (otr_status == "'+FINISHED+'") { ]}' +
  664. '<span class="icon-unlocked"></span>'+
  665. '{[ } ]}' +
  666. '<ul>'+
  667. '{[ if (otr_status == "'+UNENCRYPTED+'") { ]}' +
  668. '<li><a class="start-otr" href="#">'+__('Start encrypted conversation')+'</a></li>'+
  669. '{[ } ]}' +
  670. '{[ if (otr_status != "'+UNENCRYPTED+'") { ]}' +
  671. '<li><a class="start-otr" href="#">'+__('Refresh encrypted conversation')+'</a></li>'+
  672. '<li><a class="end-otr" href="#">'+__('End encrypted conversation')+'</a></li>'+
  673. '<li><a class="auth-otr" data-scheme="smp" href="#">'+__('Verify with SMP')+'</a></li>'+
  674. '{[ } ]}' +
  675. '{[ if (otr_status == "'+UNVERIFIED+'") { ]}' +
  676. '<li><a class="auth-otr" data-scheme="fingerprint" href="#">'+__('Verify with fingerprints')+'</a></li>'+
  677. '{[ } ]}' +
  678. '<li><a href="http://www.cypherpunks.ca/otr/help/3.2.0/levels.php" target="_blank">'+__("What\'s this?")+'</a></li>'+
  679. '</ul>'+
  680. '</li>'+
  681. '{[ } ]}'
  682. ),
  683. message_template: _.template(
  684. '<div class="chat-message {{extra_classes}}">' +
  685. '<span class="chat-message-{{sender}}">{{time}} {{username}}:&nbsp;</span>' +
  686. '<span class="chat-message-content">{{message}}</span>' +
  687. '</div>'),
  688. action_template: _.template(
  689. '<div class="chat-message {{extra_classes}}">' +
  690. '<span class="chat-message-{{sender}}">{{time}} **{{username}} </span>' +
  691. '<span class="chat-message-content">{{message}}</span>' +
  692. '</div>'),
  693. new_day_template: _.template(
  694. '<time class="chat-date" datetime="{{isodate}}">{{datestring}}</time>'
  695. ),
  696. initialize: function (){
  697. this.model.messages.on('add', this.onMessageAdded, this);
  698. this.model.on('show', this.show, this);
  699. this.model.on('destroy', this.hide, this);
  700. this.model.on('change', this.onChange, this);
  701. this.model.on('showOTRError', this.showOTRError, this);
  702. this.model.on('buddyStartsOTR', this.buddyStartsOTR, this);
  703. this.model.on('showHelpMessages', this.showHelpMessages, this);
  704. this.model.on('sendMessageStanza', this.sendMessageStanza, this);
  705. this.model.on('showSentOTRMessage', function (text) {
  706. this.showOTRMessage(text, 'me');
  707. }, this);
  708. this.model.on('showReceivedOTRMessage', function (text) {
  709. this.showOTRMessage(text, 'them');
  710. }, this);
  711. this.updateVCard();
  712. this.$el.appendTo(converse.chatboxesview.$el);
  713. this.render().show().model.messages.fetch({add: true});
  714. if (this.model.get('status')) {
  715. this.showStatusMessage(this.model.get('status'));
  716. }
  717. },
  718. render: function () {
  719. this.$el.attr('id', this.model.get('box_id'))
  720. .html(this.template(this.model.toJSON()));
  721. this.renderToolbar().renderAvatar();
  722. return this;
  723. },
  724. showStatusNotification: function (message, replace) {
  725. var $chat_content = this.$el.find('.chat-content');
  726. $chat_content.find('div.chat-event').remove().end()
  727. .append($('<div class="chat-event"></div>').text(message));
  728. this.scrollDown();
  729. },
  730. insertEmoticons: function (text) {
  731. if (converse.show_emoticons) {
  732. text = text.replace(/:\)/g, '<span class="emoticon icon-smiley"></span>');
  733. text = text.replace(/:\-\)/g, '<span class="emoticon icon-smiley"></span>');
  734. text = text.replace(/;\)/g, '<span class="emoticon icon-wink"></span>');
  735. text = text.replace(/;\-\)/g, '<span class="emoticon icon-wink"></span>');
  736. text = text.replace(/:D/g, '<span class="emoticon icon-grin"></span>');
  737. text = text.replace(/:\-D/g, '<span class="emoticon icon-grin"></span>');
  738. text = text.replace(/:P/g, '<span class="emoticon icon-tongue"></span>');
  739. text = text.replace(/:\-P/g, '<span class="emoticon icon-tongue"></span>');
  740. text = text.replace(/:p/g, '<span class="emoticon icon-tongue"></span>');
  741. text = text.replace(/:\-p/g, '<span class="emoticon icon-tongue"></span>');
  742. text = text.replace(/8\)/g, '<span class="emoticon icon-cool"></span>');
  743. text = text.replace(/>:\)/g, '<span class="emoticon icon-evil"></span>');
  744. text = text.replace(/:S/g, '<span class="emoticon icon-confused"></span>');
  745. text = text.replace(/:\\/g, '<span class="emoticon icon-wondering"></span>');
  746. text = text.replace(/>:\(/g, '<span class="emoticon icon-angry"></span>');
  747. text = text.replace(/:\(/g, '<span class="emoticon icon-sad"></span>');
  748. text = text.replace(/:\-\(/g, '<span class="emoticon icon-sad"></span>');
  749. text = text.replace(/:O/g, '<span class="emoticon icon-shocked"></span>');
  750. text = text.replace(/:\-O/g, '<span class="emoticon icon-shocked"></span>');
  751. text = text.replace(/\=\-O/g, '<span class="emoticon icon-shocked"></span>');
  752. text = text.replace(/\(\^.\^\)b/g, '<span class="emoticon icon-thumbs-up"></span>');
  753. text = text.replace(/<3/g, '<span class="emoticon icon-heart"></span>');
  754. }
  755. return text;
  756. },
  757. showMessage: function ($el, msg_dict) {
  758. var this_date = converse.parseISO8601(msg_dict.time),
  759. text = msg_dict.message,
  760. match = text.match(/^\/(.*?)(?: (.*))?$/),
  761. sender = msg_dict.sender,
  762. template, username;
  763. if ((match) && (match[1] === 'me')) {
  764. text = text.replace(/^\/me/, '');
  765. template = this.action_template;
  766. username = msg_dict.fullname;
  767. } else {
  768. template = this.message_template;
  769. username = sender === 'me' && __('me') || msg_dict.fullname;
  770. }
  771. $el.find('div.chat-event').remove();
  772. $el.append(
  773. template({
  774. 'sender': sender,
  775. 'time': this_date.toTimeString().substring(0,5),
  776. 'message': this.insertEmoticons(text),
  777. 'username': username,
  778. 'extra_classes': msg_dict.delayed && 'delayed' || ''
  779. }));
  780. return this.scrollDown();
  781. },
  782. showOTRMessage: function (text, sender) {
  783. /* "Off-the-record" messages are encrypted and not stored at all,
  784. * so we don't have a backbone converse.Message object to work with.
  785. */
  786. var username = sender === 'me' && sender || this.model.get('fullname');
  787. var $el = this.$el.find('.chat-content');
  788. $el.find('div.chat-event').remove();
  789. $el.append(
  790. this.message_template({
  791. 'sender': sender,
  792. 'time': (new Date()).toTimeString().substring(0,5),
  793. 'message': text,
  794. 'username': username,
  795. 'extra_classes': ''
  796. }));
  797. return this.scrollDown();
  798. },
  799. showHelpMessages: function (msgs, type) {
  800. var $chat_content = this.$el.find('.chat-content'), i,
  801. msgs_length = msgs.length;
  802. for (i=0; i<msgs_length; i++) {
  803. $chat_content.append($('<div class="chat-'+(type||'info')+'">'+msgs[i]+'</div>'));
  804. }
  805. return this.scrollDown();
  806. },
  807. onMessageAdded: function (message) {
  808. var time = message.get('time'),
  809. times = this.model.messages.pluck('time'),
  810. this_date = converse.parseISO8601(time),
  811. $chat_content = this.$el.find('.chat-content'),
  812. previous_message, idx, prev_date, isodate, text, match;
  813. // If this message is on a different day than the one received
  814. // prior, then indicate it on the chatbox.
  815. idx = _.indexOf(times, time)-1;
  816. if (idx >= 0) {
  817. previous_message = this.model.messages.at(idx);
  818. prev_date = converse.parseISO8601(previous_message.get('time'));
  819. isodate = new Date(this_date.getTime());
  820. isodate.setUTCHours(0,0,0,0);
  821. isodate = converse.toISOString(isodate);
  822. if (this.isDifferentDay(prev_date, this_date)) {
  823. $chat_content.append(this.new_day_template({
  824. isodate: isodate,
  825. datestring: this_date.toString().substring(0,15)
  826. }));
  827. }
  828. }
  829. if (message.get('composing')) {
  830. this.showStatusNotification(message.get('fullname')+' '+'is typing');
  831. return;
  832. } else {
  833. this.showMessage($chat_content, _.clone(message.attributes));
  834. }
  835. if ((message.get('sender') != 'me') && (converse.windowState == 'blur')) {
  836. converse.incrementMsgCounter();
  837. }
  838. return this.scrollDown();
  839. },
  840. isDifferentDay: function (prev_date, next_date) {
  841. return (
  842. (next_date.getDate() != prev_date.getDate()) ||
  843. (next_date.getFullYear() != prev_date.getFullYear()) ||
  844. (next_date.getMonth() != prev_date.getMonth()));
  845. },
  846. sendMessageStanza: function (text) {
  847. /*
  848. * Sends the actual XML stanza to the XMPP server.
  849. */
  850. // TODO: Look in ChatPartners to see what resources we have for the recipient.
  851. // if we have one resource, we sent to only that resources, if we have multiple
  852. // we send to the bare jid.
  853. var timestamp = (new Date()).getTime();
  854. var bare_jid = this.model.get('jid');
  855. var message = $msg({from: converse.connection.jid, to: bare_jid, type: 'chat', id: timestamp})
  856. .c('body').t(text).up()
  857. .c('active', {'xmlns': 'http://jabber.org/protocol/chatstates'});
  858. // Forward the message, so that other connected resources are also aware of it.
  859. // TODO: Forward the message only to other connected resources (inside the browser)
  860. var forwarded = $msg({to:converse.bare_jid, type:'chat', id:timestamp})
  861. .c('forwarded', {xmlns:'urn:xmpp:forward:0'})
  862. .c('delay', {xmns:'urn:xmpp:delay',stamp:timestamp}).up()
  863. .cnode(message.tree());
  864. converse.connection.send(message);
  865. converse.connection.send(forwarded);
  866. },
  867. sendMessage: function (text) {
  868. var match = text.replace(/^\s*/, "").match(/^\/(.*)\s*$/), msgs;
  869. if (match) {
  870. if (match[1] === "clear") {
  871. this.$el.find('.chat-content').empty();
  872. this.model.messages.reset().localStorage._clear();
  873. return;
  874. }
  875. else if (match[1] === "help") {
  876. msgs = [
  877. '<strong>/help</strong>:'+__('Show this menu')+'',
  878. '<strong>/me</strong>:'+__('Write in the third person')+'',
  879. '<strong>/clear</strong>:'+__('Remove messages')+''
  880. ];
  881. this.showHelpMessages(msgs);
  882. return;
  883. } else if ((converse.allow_otr) || (match[1] === "endotr")) {
  884. return this.endOTR();
  885. } else if ((converse.allow_otr) || (match[1] === "otr")) {
  886. return this.model.initiateOTR();
  887. }
  888. }
  889. if (_.contains([UNVERIFIED, VERIFIED], this.model.get('otr_status'))) {
  890. // Off-the-record encryption is active
  891. this.model.otr.sendMsg(text);
  892. this.model.trigger('showSentOTRMessage', text);
  893. } else {
  894. // We only save unencrypted messages.
  895. this.model.messages.create({
  896. fullname: converse.xmppstatus.get('fullname')||converse.bare_jid,
  897. sender: 'me',
  898. time: converse.toISOString(new Date()),
  899. message: text
  900. });
  901. this.sendMessageStanza(text);
  902. }
  903. },
  904. keyPressed: function (ev) {
  905. var $textarea = $(ev.target),
  906. message, notify, composing;
  907. if(ev.keyCode == KEY.ENTER) {
  908. ev.preventDefault();
  909. message = $textarea.val();
  910. $textarea.val('').focus();
  911. if (message !== '') {
  912. if (this.model.get('chatroom')) {
  913. this.sendChatRoomMessage(message);
  914. } else {
  915. this.sendMessage(message);
  916. }
  917. }
  918. this.$el.data('composing', false);
  919. } else if (!this.model.get('chatroom')) {
  920. // composing data is only for single user chat
  921. composing = this.$el.data('composing');
  922. if (!composing) {
  923. if (ev.keyCode != 47) {
  924. // We don't send composing messages if the message
  925. // starts with forward-slash.
  926. notify = $msg({'to':this.model.get('jid'), 'type': 'chat'})
  927. .c('composing', {'xmlns':'http://jabber.org/protocol/chatstates'});
  928. converse.connection.send(notify);
  929. }
  930. this.$el.data('composing', true);
  931. }
  932. }
  933. },
  934. insertSmiley: function (ev) {
  935. ev.stopPropagation();
  936. this.$el.find('.toggle-smiley ul').slideToggle(200);
  937. var $textbox = this.$el.find('textarea.chat-textarea');
  938. var value = $textbox.val();
  939. var $target = $(ev.target);
  940. $target = $target.is('a') ? $target : $target.children('a');
  941. if (value && (value[value.length-1] !== ' ')) {
  942. value = value + ' ';
  943. }
  944. $textbox.val(value+$target.data('emoticon')+' ');
  945. },
  946. toggleSmileyMenu: function (ev) {
  947. ev.stopPropagation();
  948. this.$el.find('.toggle-smiley ul').slideToggle(200);
  949. },
  950. toggleOTRMenu: function (ev) {
  951. ev.stopPropagation();
  952. this.$el.find('.toggle-otr ul').slideToggle(200);
  953. },
  954. showOTRError: function (msg) {
  955. if (msg == 'Message cannot be sent at this time.') {
  956. this.showHelpMessages(
  957. [__('Your message could not be sent')], 'error');
  958. } else if (msg == 'Received an unencrypted message.') {
  959. this.showHelpMessages(
  960. [__('We received an unencrypted message')], 'error');
  961. } else if (msg == 'Received an unreadable encrypted message.') {
  962. this.showHelpMessages(
  963. [__('We received an unreadable encrypted message')],
  964. 'error');
  965. } else {
  966. this.showHelpMessages(['Encryption error occured: '+msg], 'error');
  967. }
  968. console.log("OTR ERROR:"+msg);
  969. },
  970. buddyStartsOTR: function (ev) {
  971. this.showHelpMessages([__('This user has requested an encrypted session.')]);
  972. this.model.initiateOTR();
  973. },
  974. startOTRFromToolbar: function (ev) {
  975. $(ev.target).parent().parent().slideUp();
  976. ev.stopPropagation();
  977. this.model.initiateOTR();
  978. },
  979. endOTR: function (ev) {
  980. this.model.endOTR();
  981. },
  982. authOTR: function (ev) {
  983. var scheme = $(ev.target).data().scheme;
  984. var result, question, answer;
  985. if (scheme === 'fingerprint') {
  986. result = confirm(__('Here are the fingerprints, please confirm them with %1$s, outside of this chat.\n\nFingerprint for you, %2$s: %3$s\n\nFingerprint for %1$s: %4$s\n\nIf you have confirmed that the fingerprints match, click OK, otherwise click Cancel.', [
  987. this.model.get('fullname'),
  988. converse.xmppstatus.get('fullname')||converse.bare_jid,
  989. this.model.otr.priv.fingerprint(),
  990. this.model.otr.their_priv_pk.fingerprint()
  991. ]
  992. ));
  993. if (result === true) {
  994. this.model.save({'otr_status': VERIFIED});
  995. } else {
  996. this.model.save({'otr_status': UNVERIFIED});
  997. }
  998. } else if (scheme === 'smp') {
  999. alert(__('You will be prompted to provide a security question and then an answer to that question.\n\nYour buddy will then be prompted the same question and if they type the exact same answer (case sensitive), their identity will have been verified.'));
  1000. question = prompt(__('What is your security question?'));
  1001. if (question) {
  1002. answer = prompt(__('What is the answer to the security question?'));
  1003. this.model.otr.smpSecret(answer, question);
  1004. }
  1005. } else {
  1006. this.showHelpMessages([__('Invalid authentication scheme provided')], 'error');
  1007. }
  1008. },
  1009. onChange: function (item, changed) {
  1010. if (_.has(item.changed, 'chat_status')) {
  1011. var chat_status = item.get('chat_status'),
  1012. fullname = item.get('fullname');
  1013. if (this.$el.is(':visible')) {
  1014. if (chat_status === 'offline') {
  1015. this.showStatusNotification(fullname+' '+'has gone offline');
  1016. } else if (chat_status === 'away') {
  1017. this.showStatusNotification(fullname+' '+'has gone away');
  1018. } else if ((chat_status === 'dnd')) {
  1019. this.showStatusNotification(fullname+' '+'is busy');
  1020. } else if (chat_status === 'online') {
  1021. this.$el.find('div.chat-event').remove();
  1022. }
  1023. }
  1024. }
  1025. if (_.has(item.changed, 'status')) {
  1026. this.showStatusMessage(item.get('status'));
  1027. }
  1028. if (_.has(item.changed, 'image')) {
  1029. this.renderAvatar();
  1030. }
  1031. if (_.has(item.changed, 'otr_status')) {
  1032. this.renderToolbar().informOTRChange();
  1033. }
  1034. // TODO check for changed fullname as well
  1035. },
  1036. showStatusMessage: function (msg) {
  1037. this.$el.find('p.user-custom-message').text(msg).attr('title', msg);
  1038. },
  1039. closeChat: function () {
  1040. if (converse.connection) {
  1041. this.model.destroy();
  1042. } else {
  1043. this.model.trigger('hide');
  1044. }
  1045. },
  1046. updateVCard: function () {
  1047. var jid = this.model.get('jid'),
  1048. rosteritem = converse.roster.get(jid);
  1049. if ((rosteritem) && (!rosteritem.get('vcard_updated'))) {
  1050. converse.getVCard(
  1051. jid,
  1052. $.proxy(function (jid, fullname, image, image_type, url) {
  1053. this.model.save({
  1054. 'fullname' : fullname || jid,
  1055. 'url': url,
  1056. 'image_type': image_type,
  1057. 'image': image
  1058. });
  1059. }, this),
  1060. $.proxy(function (stanza) {
  1061. converse.log("ChatBoxView.initialize: An error occured while fetching vcard");
  1062. }, this)
  1063. );
  1064. }
  1065. },
  1066. informOTRChange: function () {
  1067. var data = this.model.toJSON();
  1068. var msgs = [];
  1069. if (data.otr_status == UNENCRYPTED) {
  1070. msgs.push(__("Your messages are not encrypted anymore"));
  1071. } else if (data.otr_status == UNVERIFIED){
  1072. msgs.push(__("Your messages are now encrypted but your buddy's identity has not been verified."));
  1073. } else if (data.otr_status == VERIFIED){
  1074. msgs.push(__("Your buddy's identify has been verified."));
  1075. } else if (data.otr_status == FINISHED){
  1076. msgs.push(__("Your buddy has ended encryption on their end, you should do the same."));
  1077. }
  1078. return this.showHelpMessages(msgs);
  1079. },
  1080. renderToolbar: function () {
  1081. if (converse.show_toolbar) {
  1082. var data = this.model.toJSON();
  1083. if (data.otr_status == UNENCRYPTED) {
  1084. data.otr_tooltip = __('Your messages are not encrypted. Click here to enable OTR encryption.');
  1085. } else if (data.otr_status == UNVERIFIED){
  1086. data.otr_tooltip = __('Your messages are encrypted, but your buddy has not been verified.');
  1087. } else if (data.otr_status == VERIFIED){
  1088. data.otr_tooltip = __('Your messages are encrypted and your buddy verified.');
  1089. } else if (data.otr_status == FINISHED){
  1090. data.otr_tooltip = __('Your buddy has closed their end of the private session, you should do the same');
  1091. }
  1092. data.allow_otr = converse.allow_otr;
  1093. data.show_emoticons = converse.show_emoticons;
  1094. data.otr_translated_status = OTR_TRANSLATED_MAPPING[data.otr_status];
  1095. data.otr_status_class = OTR_CLASS_MAPPING[data.otr_status];
  1096. this.$el.find('.chat-toolbar').html(this.toolbar_template(data));
  1097. }
  1098. return this;
  1099. },
  1100. renderAvatar: function () {
  1101. if (!this.model.get('image')) {
  1102. return;
  1103. }
  1104. var img_src = 'data:'+this.model.get('image_type')+';base64,'+this.model.get('image'),
  1105. canvas = $('<canvas height="33px" width="33px" class="avatar"></canvas>'),
  1106. ctx = canvas.get(0).getContext('2d'),
  1107. img = new Image(); // Create new Image object
  1108. img.onload = function() {
  1109. var ratio = img.width/img.height;
  1110. ctx.drawImage(img, 0,0, 35*ratio, 35);
  1111. };
  1112. img.src = img_src;
  1113. this.$el.find('.chat-title').before(canvas);
  1114. return this;
  1115. },
  1116. focus: function () {
  1117. this.$el.find('.chat-textarea').focus();
  1118. return this;
  1119. },
  1120. hide: function () {
  1121. if (converse.animate) {
  1122. this.$el.hide('fast');
  1123. } else {
  1124. this.$el.hide();
  1125. }
  1126. },
  1127. show: function () {
  1128. if (this.$el.is(':visible') && this.$el.css('opacity') == "1") {
  1129. return this.focus();
  1130. }
  1131. if (converse.animate) {
  1132. this.$el.css({'opacity': 0, 'display': 'inline'}).animate({opacity: '1'}, 200);
  1133. } else {
  1134. this.$el.css({'opacity': 1, 'display': 'inline'});
  1135. }
  1136. if (converse.connection) {
  1137. // Without a connection, we haven't yet initialized
  1138. // localstorage
  1139. this.model.save();
  1140. }
  1141. return this;
  1142. },
  1143. scrollDown: function () {
  1144. var $content = this.$el.find('.chat-content');
  1145. $content.scrollTop($content[0].scrollHeight);
  1146. return this;
  1147. }
  1148. });
  1149. this.ContactsPanel = Backbone.View.extend({
  1150. tagName: 'div',
  1151. className: 'oc-chat-content',
  1152. id: 'users',
  1153. events: {
  1154. 'click a.toggle-xmpp-contact-form': 'toggleContactForm',
  1155. 'submit form.add-xmpp-contact': 'addContactFromForm',
  1156. 'submit form.search-xmpp-contact': 'searchContacts',
  1157. 'click a.subscribe-to-user': 'addContactFromList'
  1158. },
  1159. tab_template: _.template('<li><a class="s current" href="#users">'+__('Contacts')+'</a></li>'),
  1160. template: _.template(
  1161. '<form class="set-xmpp-status" action="" method="post">'+
  1162. '<span id="xmpp-status-holder">'+
  1163. '<select id="select-xmpp-status" style="display:none">'+
  1164. '<option value="online">'+__('Online')+'</option>'+
  1165. '<option value="dnd">'+__('Busy')+'</option>'+
  1166. '<option value="away">'+__('Away')+'</option>'+
  1167. '<option value="offline">'+__('Offline')+'</option>'+
  1168. '</select>'+
  1169. '</span>'+
  1170. '</form>'
  1171. ),
  1172. add_contact_dropdown_template: _.template(
  1173. '<dl class="add-converse-contact dropdown">' +
  1174. '<dt id="xmpp-contact-search" class="fancy-dropdown">' +
  1175. '<a class="toggle-xmpp-contact-form" href="#"'+
  1176. 'title="'+__('Click to add new chat contacts')+'">'+
  1177. '<span class="icon-plus"></span>'+__('Add a contact')+'</a>' +
  1178. '</dt>' +
  1179. '<dd class="search-xmpp" style="display:none"><ul></ul></dd>' +
  1180. '</dl>'
  1181. ),
  1182. add_contact_form_template: _.template(
  1183. '<li>'+
  1184. '<form class="add-xmpp-contact">' +
  1185. '<input type="text" name="identifier" class="username" placeholder="'+__('Contact username')+'"/>' +
  1186. '<button type="submit">'+__('Add')+'</button>' +
  1187. '</form>'+
  1188. '<li>'
  1189. ),
  1190. search_contact_template: _.template(
  1191. '<li>'+
  1192. '<form class="search-xmpp-contact">' +
  1193. '<input type="text" name="identifier" class="username" placeholder="'+__('Contact name')+'"/>' +
  1194. '<button type="submit">'+__('Search')+'</button>' +
  1195. '</form>'+
  1196. '<li>'
  1197. ),
  1198. initialize: function (cfg) {
  1199. cfg.$parent.append(this.$el);
  1200. this.$tabs = cfg.$parent.parent().find('#controlbox-tabs');
  1201. },
  1202. render: function () {
  1203. var markup;
  1204. var widgets = this.template();
  1205. this.$tabs.append(this.tab_template());
  1206. if (converse.xhr_user_search) {
  1207. markup = this.search_contact_template();
  1208. } else {
  1209. markup = this.add_contact_form_template();
  1210. }
  1211. if (converse.allow_contact_requests) {
  1212. widgets += this.add_contact_dropdown_template();
  1213. }
  1214. this.$el.html(widgets);
  1215. this.$el.find('.search-xmpp ul').append(markup);
  1216. this.$el.append(converse.rosterview.$el);
  1217. return this;
  1218. },
  1219. toggleContactForm: function (ev) {
  1220. ev.preventDefault();
  1221. this.$el.find('.search-xmpp').toggle('fast', function () {
  1222. if ($(this).is(':visible')) {
  1223. $(this).find('input.username').focus();
  1224. }
  1225. });
  1226. },
  1227. searchContacts: function (ev) {
  1228. ev.preventDefault();
  1229. $.getJSON(portal_url + "/search-users?q=" + $(ev.target).find('input.username').val(), function (data) {
  1230. var $ul= $('.search-xmpp ul');
  1231. $ul.find('li.found-user').remove();
  1232. $ul.find('li.chat-info').remove();
  1233. if (!data.length) {
  1234. $ul.append('<li class="chat-info">'+__('No users found')+'</li>');
  1235. }
  1236. $(data).each(function (idx, obj) {
  1237. $ul.append(
  1238. $('<li class="found-user"></li>')
  1239. .append(
  1240. $('<a class="subscribe-to-user" href="#" title="'+__('Click to add as a chat contact')+'"></a>')
  1241. .attr('data-recipient', Strophe.escapeNode(obj.id)+'@'+converse.domain)
  1242. .text(obj.fullname)
  1243. )
  1244. );
  1245. });
  1246. });
  1247. },
  1248. addContactFromForm: function (ev) {
  1249. ev.preventDefault();
  1250. var $input = $(ev.target).find('input');
  1251. var jid = $input.val();
  1252. if (! jid) {
  1253. // this is not a valid JID
  1254. $input.addClass('error');
  1255. return;
  1256. }
  1257. converse.getVCard(
  1258. jid,
  1259. $.proxy(function (jid, fullname, image, image_type, url) {
  1260. this.addContact(jid, fullname);
  1261. }, this),
  1262. $.proxy(function (stanza) {
  1263. converse.log("An error occured while fetching vcard");
  1264. var jid = $(stanza).attr('from');
  1265. this.addContact(jid, jid);
  1266. }, this));
  1267. $('.search-xmpp').hide();
  1268. },
  1269. addContactFromList: function (ev) {
  1270. ev.preventDefault();
  1271. var $target = $(ev.target),
  1272. jid = $target.attr('data-recipient'),
  1273. name = $target.text();
  1274. this.addContact(jid, name);
  1275. $target.parent().remove();
  1276. $('.search-xmpp').hide();
  1277. },
  1278. addContact: function (jid, name) {
  1279. converse.connection.roster.add(jid, name, [], function (iq) {
  1280. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  1281. });
  1282. }
  1283. });
  1284. this.RoomsPanel = Backbone.View.extend({
  1285. tagName: 'div',
  1286. id: 'chatrooms',
  1287. events: {
  1288. 'submit form.add-chatroom': 'createChatRoom',
  1289. 'click input#show-rooms': 'showRooms',
  1290. 'click a.open-room': 'createChatRoom',
  1291. 'click a.room-info': 'showRoomInfo'
  1292. },
  1293. room_template: _.template(
  1294. '<dd class="available-chatroom">'+
  1295. '<a class="open-room" data-room-jid="{{jid}}"'+
  1296. 'title="'+__('Click to open this room')+'" href="#">{{name}}</a>'+
  1297. '<a class="room-info icon-room-info" data-room-jid="{{jid}}"'+
  1298. 'title="'+__('Show more information on this room')+'" href="#">&nbsp;</a>'+
  1299. '</dd>'),
  1300. // FIXME: check markup in mockup
  1301. room_description_template: _.template(
  1302. '<div class="room-info">'+
  1303. '<p class="room-info"><strong>'+__('Description:')+'</strong> {{desc}}</p>' +
  1304. '<p class="room-info"><strong>'+__('Occupants:')+'</strong> {{occ}}</p>' +
  1305. '<p class="room-info"><strong>'+__('Features:')+'</strong> <ul>'+
  1306. '{[ if (passwordprotected) { ]}' +
  1307. '<li class="room-info locked">'+__('Requires authentication')+'</li>' +
  1308. '{[ } ]}' +
  1309. '{[ if (hidden) { ]}' +
  1310. '<li class="room-info">'+__('Hidden')+'</li>' +
  1311. '{[ } ]}' +
  1312. '{[ if (membersonly) { ]}' +
  1313. '<li class="room-info">'+__('Requires an invitation')+'</li>' +
  1314. '{[ } ]}' +
  1315. '{[ if (moderated) { ]}' +
  1316. '<li class="room-info">'+__('Moderated')+'</li>' +
  1317. '{[ } ]}' +
  1318. '{[ if (nonanonymous) { ]}' +
  1319. '<li class="room-info">'+__('Non-anonymous')+'</li>' +
  1320. '{[ } ]}' +
  1321. '{[ if (open) { ]}' +
  1322. '<li class="room-info">'+__('Open room')+'</li>' +
  1323. '{[ } ]}' +
  1324. '{[ if (persistent) { ]}' +
  1325. '<li class="room-info">'+__('Permanent room')+'</li>' +
  1326. '{[ } ]}' +
  1327. '{[ if (publicroom) { ]}' +
  1328. '<li class="room-info">'+__('Public')+'</li>' +
  1329. '{[ } ]}' +
  1330. '{[ if (semianonymous) { ]}' +
  1331. '<li class="room-info">'+__('Semi-anonymous')+'</li>' +
  1332. '{[ } ]}' +
  1333. '{[ if (temporary) { ]}' +
  1334. '<li class="room-info">'+__('Temporary room')+'</li>' +
  1335. '{[ } ]}' +
  1336. '{[ if (unmoderated) { ]}' +
  1337. '<li class="room-info">'+__('Unmoderated')+'</li>' +
  1338. '{[ } ]}' +
  1339. '</p>' +
  1340. '</div>'
  1341. ),
  1342. tab_template: _.template('<li><a class="s" href="#chatrooms">'+__('Rooms')+'</a></li>'),
  1343. template: _.template(
  1344. '<form class="add-chatroom" action="" method="post">'+
  1345. '<input type="text" name="chatroom" class="new-chatroom-name" placeholder="'+__('Room name')+'"/>'+
  1346. '<input type="text" name="nick" class="new-chatroom-nick" placeholder="'+__('Nickname')+'"/>'+
  1347. '<input type="{{ server_input_type }}" name="server" class="new-chatroom-server" placeholder="'+__('Server')+'"/>'+
  1348. '<input type="submit" name="join" value="'+__('Join')+'"/>'+
  1349. '<input type="button" name="show" id="show-rooms" value="'+__('Show rooms')+'"/>'+
  1350. '</form>'+
  1351. '<dl id="available-chatrooms"></dl>'),
  1352. initialize: function (cfg) {
  1353. cfg.$parent.append(
  1354. this.$el.html(
  1355. this.template({
  1356. server_input_type: converse.hide_muc_server && 'hidden' || 'text'
  1357. })
  1358. ).hide());
  1359. this.$tabs = cfg.$parent.parent().find('#controlbox-tabs');
  1360. this.on('update-rooms-list', function (ev) {
  1361. this.updateRoomsList();
  1362. });
  1363. converse.xmppstatus.on("change", $.proxy(function (model) {
  1364. if (!(_.has(model.changed, 'fullname'))) {
  1365. return;
  1366. }
  1367. var $nick = this.$el.find('input.new-chatroom-nick');
  1368. if (! $nick.is(':focus')) {
  1369. $nick.val(model.get('fullname'));
  1370. }
  1371. }, this));
  1372. },
  1373. render: function () {
  1374. this.$tabs.append(this.tab_template());
  1375. return this;
  1376. },
  1377. informNoRoomsFound: function () {
  1378. var $available_chatrooms = this.$el.find('#available-chatrooms');
  1379. // # For translators: %1$s is a variable and will be replaced with the XMPP server name
  1380. $available_chatrooms.html('<dt>'+__('No rooms on %1$s',this.muc_domain)+'</dt>');
  1381. $('input#show-rooms').show().siblings('span.spinner').remove();
  1382. },
  1383. updateRoomsList: function (domain) {
  1384. converse.connection.muc.listRooms(
  1385. this.muc_domain,
  1386. $.proxy(function (iq) { // Success
  1387. var name, jid, i, fragment,
  1388. that = this,
  1389. $available_chatrooms = this.$el.find('#available-chatrooms');
  1390. this.rooms = $(iq).find('query').find('item');
  1391. if (this.rooms.length) {
  1392. // # For translators: %1$s is a variable and will be
  1393. // # replaced with the XMPP server name
  1394. $available_chatrooms.html('<dt>'+__('Rooms on %1$s',this.muc_domain)+'</dt>');
  1395. fragment = document.createDocumentFragment();
  1396. for (i=0; i<this.rooms.length; i++) {
  1397. name = Strophe.unescapeNode($(this.rooms[i]).attr('name')||$(this.rooms[i]).attr('jid'));
  1398. jid = $(this.rooms[i]).attr('jid');
  1399. fragment.appendChild($(this.room_template({
  1400. 'name':name,
  1401. 'jid':jid
  1402. }))[0]);
  1403. }
  1404. $available_chatrooms.append(fragment);
  1405. $('input#show-rooms').show().siblings('span.spinner').remove();
  1406. } else {
  1407. this.informNoRoomsFound();
  1408. }
  1409. return true;
  1410. }, this),
  1411. $.proxy(function (iq) { // Failure
  1412. this.informNoRoomsFound();
  1413. }, this));
  1414. },
  1415. showRooms: function (ev) {
  1416. var $available_chatrooms = this.$el.find('#available-chatrooms');
  1417. var $server = this.$el.find('input.new-chatroom-server');
  1418. var server = $server.val();
  1419. if (!server) {
  1420. $server.addClass('error');
  1421. return;
  1422. }
  1423. this.$el.find('input.new-chatroom-name').removeClass('error');
  1424. $server.removeClass('error');
  1425. $available_chatrooms.empty();
  1426. $('input#show-rooms').hide().after('<span class="spinner"/>');
  1427. this.muc_domain = server;
  1428. this.updateRoomsList();
  1429. },
  1430. showRoomInfo: function (ev) {
  1431. var target = ev.target,
  1432. $dd = $(target).parent('dd'),
  1433. $div = $dd.find('div.room-info');
  1434. if ($div.length) {
  1435. $div.remove();
  1436. } else {
  1437. $dd.find('span.spinner').remove();
  1438. $dd.append('<span class="spinner hor_centered"/>');
  1439. converse.connection.disco.info(
  1440. $(target).attr('data-room-jid'),
  1441. null,
  1442. $.proxy(function (stanza) {
  1443. var $stanza = $(stanza);
  1444. // All MUC features found here: http://xmpp.org/registrar/disco-features.html
  1445. $dd.find('span.spinner').replaceWith(
  1446. this.room_description_template({
  1447. 'desc': $stanza.find('field[var="muc#roominfo_description"] value').text(),
  1448. 'occ': $stanza.find('field[var="muc#roominfo_occupants"] value').text(),
  1449. 'hidden': $stanza.find('feature[var="muc_hidden"]').length,
  1450. 'membersonly': $stanza.find('feature[var="muc_membersonly"]').length,
  1451. 'moderated': $stanza.find('feature[var="muc_moderated"]').length,
  1452. 'nonanonymous': $stanza.find('feature[var="muc_nonanonymous"]').length,
  1453. 'open': $stanza.find('feature[var="muc_open"]').length,
  1454. 'passwordprotected': $stanza.find('feature[var="muc_passwordprotected"]').length,
  1455. 'persistent': $stanza.find('feature[var="muc_persistent"]').length,
  1456. 'publicroom': $stanza.find('feature[var="muc_public"]').length,
  1457. 'semianonymous': $stanza.find('feature[var="muc_semianonymous"]').length,
  1458. 'temporary': $stanza.find('feature[var="muc_temporary"]').length,
  1459. 'unmoderated': $stanza.find('feature[var="muc_unmoderated"]').length
  1460. }));
  1461. }, this));
  1462. }
  1463. },
  1464. createChatRoom: function (ev) {
  1465. ev.preventDefault();
  1466. var name, $name,
  1467. server, $server,
  1468. jid,
  1469. $nick = this.$el.find('input.new-chatroom-nick'),
  1470. nick = $nick.val(),
  1471. chatroom;
  1472. if (!nick) { $nick.addClass('error'); }
  1473. else { $nick.removeClass('error'); }
  1474. if (ev.type === 'click') {
  1475. jid = $(ev.target).attr('data-room-jid');
  1476. } else {
  1477. $name = this.$el.find('input.new-chatroom-name');
  1478. $server= this.$el.find('input.new-chatroom-server');
  1479. server = $server.val();
  1480. name = $name.val().trim().toLowerCase();
  1481. $name.val(''); // Clear the input
  1482. if (name && server) {
  1483. jid = Strophe.escapeNode(name) + '@' + server;
  1484. $name.removeClass('error');
  1485. $server.removeClass('error');
  1486. this.muc_domain = server;
  1487. } else {
  1488. if (!name) { $name.addClass('error'); }
  1489. if (!server) { $server.addClass('error'); }
  1490. return;
  1491. }
  1492. }
  1493. if (!nick) { return; }
  1494. chatroom = converse.chatboxesview.showChatBox({
  1495. 'id': jid,
  1496. 'jid': jid,
  1497. 'name': Strophe.unescapeNode(Strophe.getNodeFromJid(jid)),
  1498. 'nick': nick,
  1499. 'chatroom': true,
  1500. 'box_id' : hex_sha1(jid)
  1501. });
  1502. if (!chatroom.get('connected')) {
  1503. converse.chatboxesview.views[jid].connect(null);
  1504. }
  1505. }
  1506. });
  1507. this.ControlBoxView = converse.ChatBoxView.extend({
  1508. tagName: 'div',
  1509. className: 'chatbox',
  1510. id: 'controlbox',
  1511. events: {
  1512. 'click a.close-chatbox-button': 'closeChat',
  1513. 'click ul#controlbox-tabs li a': 'switchTab'
  1514. },
  1515. initialize: function () {
  1516. this.$el.appendTo(converse.chatboxesview.$el);
  1517. this.model.on('change', $.proxy(function (item, changed) {
  1518. var i;
  1519. if (_.has(item.changed, 'connected')) {
  1520. this.render();
  1521. converse.features.on('add', $.proxy(this.featureAdded, this));
  1522. // Features could have been added before the controlbox was
  1523. // initialized. Currently we're only interested in MUC
  1524. var feature = converse.features.findWhere({'var': 'http://jabber.org/protocol/muc'});
  1525. if (feature) {
  1526. this.featureAdded(feature);
  1527. }
  1528. }
  1529. if (_.has(item.changed, 'visible')) {
  1530. if (item.changed.visible === true) {
  1531. this.show();
  1532. }
  1533. }
  1534. }, this));
  1535. this.model.on('show', this.show, this);
  1536. this.model.on('destroy', this.hide, this);
  1537. this.model.on('hide', this.hide, this);
  1538. if (this.model.get('visible')) {
  1539. this.show();
  1540. }
  1541. },
  1542. featureAdded: function (feature) {
  1543. if ((feature.get('var') == 'http://jabber.org/protocol/muc') && (converse.allow_muc)) {
  1544. this.roomspanel.muc_domain = feature.get('from');
  1545. var $server= this.$el.find('input.new-chatroom-server');
  1546. if (! $server.is(':focus')) {
  1547. $server.val(this.roomspanel.muc_domain);
  1548. }
  1549. if (converse.auto_list_rooms) {
  1550. this.roomspanel.trigger('update-rooms-list');
  1551. }
  1552. }
  1553. },
  1554. template: _.template(
  1555. '<div class="chat-head oc-chat-head">'+
  1556. '<ul id="controlbox-tabs"></ul>'+
  1557. '<a class="close-chatbox-button icon-close"></a>'+
  1558. '</div>'+
  1559. '<div class="controlbox-panes"></div>'
  1560. ),
  1561. switchTab: function (ev) {
  1562. ev.preventDefault();
  1563. var $tab = $(ev.target),
  1564. $sibling = $tab.parent().siblings('li').children('a'),
  1565. $tab_panel = $($tab.attr('href')),
  1566. $sibling_panel = $($sibling.attr('href'));
  1567. $sibling_panel.fadeOut('fast', function () {
  1568. $sibling.removeClass('current');
  1569. $tab.addClass('current');
  1570. $tab_panel.fadeIn('fast', function () {
  1571. });
  1572. });
  1573. },
  1574. showHelpMessages: function (msgs) {
  1575. // Override showHelpMessages in ChatBoxView, for now do nothing.
  1576. return;
  1577. },
  1578. render: function () {
  1579. if ((!converse.prebind) && (!converse.connection)) {
  1580. // Add login panel if the user still has to authenticate
  1581. this.$el.html(this.template(this.model.toJSON()));
  1582. this.loginpanel = new converse.LoginPanel({'$parent': this.$el.find('.controlbox-panes'), 'model': this});
  1583. this.loginpanel.render();
  1584. } else if (!this.contactspanel) {
  1585. this.$el.html(this.template(this.model.toJSON()));
  1586. this.contactspanel = new converse.ContactsPanel({'$parent': this.$el.find('.controlbox-panes')});
  1587. this.contactspanel.render();
  1588. converse.xmppstatusview = new converse.XMPPStatusView({'model': converse.xmppstatus});
  1589. converse.xmppstatusview.render();
  1590. if (converse.allow_muc) {
  1591. this.roomspanel = new converse.RoomsPanel({'$parent': this.$el.find('.controlbox-panes')});
  1592. this.roomspanel.render();
  1593. }
  1594. }
  1595. return this;
  1596. }
  1597. });
  1598. this.ChatRoomView = converse.ChatBoxView.extend({
  1599. length: 300,
  1600. tagName: 'div',
  1601. className: 'chatroom',
  1602. events: {
  1603. 'click a.close-chatbox-button': 'closeChat',
  1604. 'click a.configure-chatroom-button': 'configureChatRoom',
  1605. 'keypress textarea.chat-textarea': 'keyPressed'
  1606. },
  1607. info_template: _.template('<div class="chat-info">{{message}}</div>'),
  1608. sendChatRoomMessage: function (body) {
  1609. var match = body.replace(/^\s*/, "").match(/^\/(.*?)(?: (.*))?$/) || [false],
  1610. $chat_content;
  1611. switch (match[1]) {
  1612. case 'msg':
  1613. // TODO: Private messages
  1614. break;
  1615. case 'clear':
  1616. this.$el.find('.chat-content').empty();
  1617. break;
  1618. case 'topic':
  1619. converse.connection.muc.setTopic(this.model.get('jid'), match[2]);
  1620. break;
  1621. case 'kick':
  1622. converse.connection.muc.kick(this.model.get('jid'), match[2]);
  1623. break;
  1624. case 'ban':
  1625. converse.connection.muc.ban(this.model.get('jid'), match[2]);
  1626. break;
  1627. case 'op':
  1628. converse.connection.muc.op(this.model.get('jid'), match[2]);
  1629. break;
  1630. case 'deop':
  1631. converse.connection.muc.deop(this.model.get('jid'), match[2]);
  1632. break;
  1633. case 'help':
  1634. $chat_content = this.$el.find('.chat-content');
  1635. msgs = [
  1636. '<strong>/help</strong>:'+__('Show this menu')+'',
  1637. '<strong>/me</strong>:'+__('Write in the third person')+'',
  1638. '<strong>/topic</strong>:'+__('Set chatroom topic')+'',
  1639. '<strong>/kick</strong>:'+__('Kick user from chatroom')+'',
  1640. '<strong>/ban</strong>:'+__('Ban user from chatroom')+'',
  1641. '<strong>/clear</strong>:'+__('Remove messages')+''
  1642. ];
  1643. this.showHelpMessages(msgs);
  1644. break;
  1645. default:
  1646. this.last_msgid = converse.connection.muc.groupchat(this.model.get('jid'), body);
  1647. break;
  1648. }
  1649. },
  1650. template: _.template(
  1651. '<div class="chat-head chat-head-chatroom">' +
  1652. '<a class="close-chatbox-button icon-close"></a>' +
  1653. '<a class="configure-chatroom-button icon-wrench" style="display:none"></a>' +
  1654. '<div class="chat-title"> {{ name }} </div>' +
  1655. '<p class="chatroom-topic"><p/>' +
  1656. '</div>' +
  1657. '<div class="chat-body">' +
  1658. '<span class="spinner centered"/>' +
  1659. '</div>'),
  1660. chatarea_template: _.template(
  1661. '<div class="chat-area">' +
  1662. '<div class="chat-content"></div>' +
  1663. '<form class="sendXMPPMessage" action="" method="post">' +
  1664. '<textarea type="text" class="chat-textarea" ' +
  1665. 'placeholder="'+__('Message')+'"/>' +
  1666. '</form>' +
  1667. '</div>' +
  1668. '<div class="participants">' +
  1669. '<ul class="participant-list"></ul>' +
  1670. '</div>'
  1671. ),
  1672. render: function () {
  1673. this.$el.attr('id', this.model.get('box_id'))
  1674. .html(this.template(this.model.toJSON()));
  1675. return this;
  1676. },
  1677. renderChatArea: function () {
  1678. if (!this.$el.find('.chat-area').length) {
  1679. this.$el.find('.chat-body').empty().append(this.chatarea_template());
  1680. }
  1681. return this;
  1682. },
  1683. connect: function (password) {
  1684. if (_.has(converse.connection.muc.rooms, this.model.get('jid'))) {
  1685. // If the room exists, it already has event listeners, so we
  1686. // doing add them again.
  1687. converse.connection.muc.join(
  1688. this.model.get('jid'), this.model.get('nick'), null, null, null, password);
  1689. } else {
  1690. converse.connection.muc.join(
  1691. this.model.get('jid'),
  1692. this.model.get('nick'),
  1693. $.proxy(this.onChatRoomMessage, this),
  1694. $.proxy(this.onChatRoomPresence, this),
  1695. $.proxy(this.onChatRoomRoster, this),
  1696. password);
  1697. }
  1698. },
  1699. initialize: function () {
  1700. this.connect(null);
  1701. this.model.messages.on('add', this.onMessageAdded, this);
  1702. this.model.on('destroy', function (model, response, options) {
  1703. this.$el.hide('fast');
  1704. converse.connection.muc.leave(
  1705. this.model.get('jid'),
  1706. this.model.get('nick'),
  1707. $.proxy(this.onLeave, this),
  1708. undefined);
  1709. },
  1710. this);
  1711. this.$el.appendTo(converse.chatboxesview.$el);
  1712. this.render().show().model.messages.fetch({add: true});
  1713. },
  1714. onLeave: function () {
  1715. this.model.set('connected', false);
  1716. },
  1717. form_input_template: _.template('<label>{{label}}<input name="{{name}}" type="{{type}}" value="{{value}}"></label>'),
  1718. select_option_template: _.template('<option value="{{value}}">{{label}}</option>'),
  1719. form_select_template: _.template('<label>{{label}}<select name="{{name}}">{{options}}</select></label>'),
  1720. form_checkbox_template: _.template('<label>{{label}}<input name="{{name}}" type="{{type}}" {{checked}}"></label>'),
  1721. renderConfigurationForm: function (stanza) {
  1722. var $form= this.$el.find('form.chatroom-form'),
  1723. $stanza = $(stanza),
  1724. $fields = $stanza.find('field'),
  1725. title = $stanza.find('title').text(),
  1726. instructions = $stanza.find('instructions').text(),
  1727. i, j, options=[];
  1728. var input_types = {
  1729. 'text-private': 'password',
  1730. 'text-single': 'textline',
  1731. 'boolean': 'checkbox',
  1732. 'hidden': 'hidden',
  1733. 'list-single': 'dropdown'
  1734. };
  1735. $form.find('span.spinner').remove();
  1736. $form.append($('<legend>').text(title));
  1737. if (instructions != title) {
  1738. $form.append($('<p>').text(instructions));
  1739. }
  1740. for (i=0; i<$fields.length; i++) {
  1741. $field = $($fields[i]);
  1742. if ($field.attr('type') == 'list-single') {
  1743. options = [];
  1744. $options = $field.find('option');
  1745. for (j=0; j<$options.length; j++) {
  1746. options.push(this.select_option_template({
  1747. value: $($options[j]).find('value').text(),
  1748. label: $($options[j]).attr('label')
  1749. }));
  1750. }
  1751. $form.append(this.form_select_template({
  1752. name: $field.attr('var'),
  1753. label: $field.attr('label'),
  1754. options: options.join('')
  1755. }));
  1756. } else if ($field.attr('type') == 'boolean') {
  1757. $form.append(this.form_checkbox_template({
  1758. name: $field.attr('var'),
  1759. type: input_types[$field.attr('type')],
  1760. label: $field.attr('label') || '',
  1761. checked: $field.find('value').text() === "1" && 'checked="1"' || ''
  1762. }));
  1763. } else {
  1764. $form.append(this.form_input_template({
  1765. name: $field.attr('var'),
  1766. type: input_types[$field.attr('type')],
  1767. label: $field.attr('label') || '',
  1768. value: $field.find('value').text()
  1769. }));
  1770. }
  1771. }
  1772. $form.append('<input type="submit" value="'+__('Save')+'"/>');
  1773. $form.append('<input type="button" value="'+__('Cancel')+'"/>');
  1774. $form.on('submit', $.proxy(this.saveConfiguration, this));
  1775. $form.find('input[type=button]').on('click', $.proxy(this.cancelConfiguration, this));
  1776. },
  1777. field_template: _.template('<field var="{{name}}"><value>{{value}}</value></field>'),
  1778. saveConfiguration: function (ev) {
  1779. ev.preventDefault();
  1780. var that = this;
  1781. var $inputs = $(ev.target).find(':input:not([type=button]):not([type=submit])'),
  1782. count = $inputs.length,
  1783. configArray = [];
  1784. $inputs.each(function () {
  1785. var $input = $(this), value;
  1786. if ($input.is('[type=checkbox]')) {
  1787. value = $input.is(':checked') && 1 || 0;
  1788. } else {
  1789. value = $input.val();
  1790. }
  1791. var cnode = $(that.field_template({
  1792. name: $input.attr('name'),
  1793. value: value
  1794. }))[0];
  1795. configArray.push(cnode);
  1796. if (!--count) {
  1797. converse.connection.muc.saveConfiguration(
  1798. that.model.get('jid'),
  1799. configArray,
  1800. $.proxy(that.onConfigSaved, that),
  1801. $.proxy(that.onErrorConfigSaved, that)
  1802. );
  1803. }
  1804. });
  1805. this.$el.find('div.chatroom-form-container').hide(
  1806. function () {
  1807. $(this).remove();
  1808. that.$el.find('.chat-area').show();
  1809. that.$el.find('.participants').show();
  1810. });
  1811. },
  1812. onConfigSaved: function (stanza) {
  1813. // XXX
  1814. },
  1815. onErrorConfigSaved: function (stanza) {
  1816. this.showStatusNotification(__("An error occurred while trying to save the form."));
  1817. },
  1818. cancelConfiguration: function (ev) {
  1819. ev.preventDefault();
  1820. var that = this;
  1821. this.$el.find('div.chatroom-form-container').hide(
  1822. function () {
  1823. $(this).remove();
  1824. that.$el.find('.chat-area').show();
  1825. that.$el.find('.participants').show();
  1826. });
  1827. },
  1828. configureChatRoom: function (ev) {
  1829. ev.preventDefault();
  1830. if (this.$el.find('div.chatroom-form-container').length) {
  1831. return;
  1832. }
  1833. this.$el.find('.chat-area').hide();
  1834. this.$el.find('.participants').hide();
  1835. this.$el.find('.chat-body').append(
  1836. $('<div class="chatroom-form-container">'+
  1837. '<form class="chatroom-form">'+
  1838. '<span class="spinner centered"/>'+
  1839. '</form>'+
  1840. '</div>'));
  1841. converse.connection.muc.configure(
  1842. this.model.get('jid'),
  1843. $.proxy(this.renderConfigurationForm, this)
  1844. );
  1845. },
  1846. submitPassword: function (ev) {
  1847. ev.preventDefault();
  1848. var password = this.$el.find('.chatroom-form').find('input[type=password]').val();
  1849. this.$el.find('.chatroom-form-container').replaceWith(
  1850. '<span class="spinner centered"/>');
  1851. this.connect(password);
  1852. },
  1853. renderPasswordForm: function () {
  1854. this.$el.find('span.centered.spinner').remove();
  1855. this.$el.find('.chat-body').append(
  1856. $('<div class="chatroom-form-container">'+
  1857. '<form class="chatroom-form">'+
  1858. '<legend>'+__('This chatroom requires a password')+'</legend>' +
  1859. '<label>'+__('Password: ')+'<input type="password" name="password"/></label>' +
  1860. '<input type="submit" value="'+__('Submit')+'/>' +
  1861. '</form>'+
  1862. '</div>'));
  1863. this.$el.find('.chatroom-form').on('submit', $.proxy(this.submitPassword, this));
  1864. },
  1865. showDisconnectMessage: function (msg) {
  1866. this.$el.find('.chat-area').remove();
  1867. this.$el.find('.participants').remove();
  1868. this.$el.find('span.centered.spinner').remove();
  1869. this.$el.find('.chat-body').append($('<p>'+msg+'</p>'));
  1870. },
  1871. infoMessages: {
  1872. 100: __('This room is not anonymous'),
  1873. 102: __('This room now shows unavailable members'),
  1874. 103: __('This room does not show unavailable members'),
  1875. 104: __('Non-privacy-related room configuration has changed'),
  1876. 170: __('Room logging is now enabled'),
  1877. 171: __('Room logging is now disabled'),
  1878. 172: __('This room is now non-anonymous'),
  1879. 173: __('This room is now semi-anonymous'),
  1880. 174: __('This room is now fully-anonymous'),
  1881. 201: __('A new room has been created'),
  1882. 210: __('Your nickname has been changed')
  1883. },
  1884. actionInfoMessages: {
  1885. /* XXX: Note the triple underscore function and not double
  1886. * underscore.
  1887. *
  1888. * This is a hack. We can't pass the strings to __ because we
  1889. * don't yet know what the variable to interpolate is.
  1890. *
  1891. * Triple underscore will just return the string again, but we
  1892. * can then at least tell gettext to scan for it so that these
  1893. * strings are picked up by the translation machinery.
  1894. */
  1895. 301: ___("<strong>%1$s</strong> has been banned"),
  1896. 307: ___("<strong>%1$s</strong> has been kicked out"),
  1897. 321: ___("<strong>%1$s</strong> has been removed because of an affiliation change"),
  1898. 322: ___("<strong>%1$s</strong> has been removed for not being a member")
  1899. },
  1900. disconnectMessages: {
  1901. 301: __('You have been banned from this room'),
  1902. 307: __('You have been kicked from this room'),
  1903. 321: __("You have been removed from this room because of an affiliation change"),
  1904. 322: __("You have been removed from this room because the room has changed to members-only and you're not a member"),
  1905. 332: __("You have been removed from this room because the MUC (Multi-user chat) service is being shut down.")
  1906. },
  1907. showStatusMessages: function ($el, is_self) {
  1908. /* Check for status codes and communicate their purpose to the user
  1909. * See: http://xmpp.org/registrar/mucstatus.html
  1910. */
  1911. var $chat_content = this.$el.find('.chat-content'),
  1912. $stats = $el.find('status'),
  1913. disconnect_msgs = [],
  1914. info_msgs = [],
  1915. action_msgs = [],
  1916. msgs, i;
  1917. for (i=0; i<$stats.length; i++) {
  1918. var stat = $stats[i].getAttribute('code');
  1919. if (is_self) {
  1920. if (_.contains(_.keys(this.disconnectMessages), stat)) {
  1921. disconnect_msgs.push(this.disconnectMessages[stat]);
  1922. }
  1923. } else {
  1924. if (_.contains(_.keys(this.infoMessages), stat)) {
  1925. info_msgs.push(this.infoMessages[stat]);
  1926. } else if (_.contains(_.keys(this.actionInfoMessages), stat)) {
  1927. action_msgs.push(
  1928. __(this.actionInfoMessages[stat], Strophe.unescapeNode(Strophe.getResourceFromJid($el.attr('from'))))
  1929. );
  1930. }
  1931. }
  1932. }
  1933. if (disconnect_msgs.length > 0) {
  1934. for (i=0; i<disconnect_msgs.length; i++) {
  1935. this.showDisconnectMessage(disconnect_msgs[i]);
  1936. }
  1937. this.model.set('connected', false);
  1938. return;
  1939. }
  1940. this.renderChatArea();
  1941. for (i=0; i<info_msgs.length; i++) {
  1942. $chat_content.append(this.info_template({message: info_msgs[i]}));
  1943. }
  1944. for (i=0; i<action_msgs.length; i++) {
  1945. $chat_content.append(this.info_template({message: action_msgs[i]}));
  1946. }
  1947. return this.scrollDown();
  1948. },
  1949. showErrorMessage: function ($error, room) {
  1950. // We didn't enter the room, so we must remove it from the MUC
  1951. // add-on
  1952. delete converse.connection.muc[room.name];
  1953. if ($error.attr('type') == 'auth') {
  1954. if ($error.find('not-authorized').length) {
  1955. this.renderPasswordForm();
  1956. } else if ($error.find('registration-required').length) {
  1957. this.showDisconnectMessage(__('You are not on the member list of this room'));
  1958. } else if ($error.find('forbidden').length) {
  1959. this.showDisconnectMessage(__('You have been banned from this room'));
  1960. }
  1961. } else if ($error.attr('type') == 'modify') {
  1962. if ($error.find('jid-malformed').length) {
  1963. this.showDisconnectMessage(__('No nickname was specified'));
  1964. }
  1965. } else if ($error.attr('type') == 'cancel') {
  1966. if ($error.find('not-allowed').length) {
  1967. this.showDisconnectMessage(__('You are not allowed to create new rooms'));
  1968. } else if ($error.find('not-acceptable').length) {
  1969. this.showDisconnectMessage(__("Your nickname doesn't conform to this room's policies"));
  1970. } else if ($error.find('conflict').length) {
  1971. this.showDisconnectMessage(__("Your nickname is already taken"));
  1972. } else if ($error.find('item-not-found').length) {
  1973. this.showDisconnectMessage(__("This room does not (yet) exist"));
  1974. } else if ($error.find('service-unavailable').length) {
  1975. this.showDisconnectMessage(__("This room has reached it's maximum number of occupants"));
  1976. }
  1977. }
  1978. },
  1979. onChatRoomPresence: function (presence, room) {
  1980. var nick = room.nick,
  1981. $presence = $(presence),
  1982. from = $presence.attr('from'),
  1983. is_self = ($presence.find("status[code='110']").length) || (from == room.name+'/'+Strophe.escapeNode(nick)),
  1984. $item;
  1985. if ($presence.attr('type') === 'error') {
  1986. this.model.set('connected', false);
  1987. this.showErrorMessage($presence.find('error'), room);
  1988. } else {
  1989. this.model.set('connected', true);
  1990. this.showStatusMessages($presence, is_self);
  1991. if (!this.model.get('connected')) {
  1992. return true;
  1993. }
  1994. if ($presence.find("status[code='201']").length) {
  1995. // This is a new chatroom. We create an instant
  1996. // chatroom, and let the user manually set any
  1997. // configuration setting.
  1998. converse.connection.muc.createInstantRoom(room.name);
  1999. }
  2000. if (is_self) {
  2001. $item = $presence.find('item');
  2002. if ($item.length) {
  2003. if ($item.attr('affiliation') == 'owner') {
  2004. this.$el.find('a.configure-chatroom-button').show();
  2005. }
  2006. }
  2007. if ($presence.find("status[code='210']").length) {
  2008. // check if server changed our nick
  2009. this.model.set({'nick': Strophe.getResourceFromJid(from)});
  2010. }
  2011. }
  2012. }
  2013. return true;
  2014. },
  2015. onChatRoomMessage: function (message) {
  2016. var $message = $(message),
  2017. body = $message.children('body').text(),
  2018. jid = $message.attr('from'),
  2019. $chat_content = this.$el.find('.chat-content'),
  2020. resource = Strophe.getResourceFromJid(jid),
  2021. sender = resource && Strophe.unescapeNode(resource) || '',
  2022. delayed = $message.find('delay').length > 0,
  2023. subject = $message.children('subject').text(),
  2024. match, template, message_datetime, message_date, dates, isodate, stamp;
  2025. if (delayed) {
  2026. stamp = $message.find('delay').attr('stamp');
  2027. message_datetime = converse.parseISO8601(stamp);
  2028. } else {
  2029. message_datetime = new Date();
  2030. }
  2031. // If this message is on a different day than the one received
  2032. // prior, then indicate it on the chatbox.
  2033. dates = $chat_content.find("time").map(function(){return $(this).attr("datetime");}).get();
  2034. message_date = new Date(message_datetime.getTime());
  2035. message_date.setUTCHours(0,0,0,0);
  2036. isodate = converse.toISOString(message_date);
  2037. if (_.indexOf(dates, isodate) == -1) {
  2038. $chat_content.append(this.new_day_template({
  2039. isodate: isodate,
  2040. datestring: message_date.toString().substring(0,15)
  2041. }));
  2042. }
  2043. this.showStatusMessages($message);
  2044. if (subject) {
  2045. this.$el.find('.chatroom-topic').text(subject).attr('title', subject);
  2046. // # For translators: the %1$s and %2$s parts will get replaced by the user and topic text respectively
  2047. // # Example: Topic set by JC Brand to: Hello World!
  2048. $chat_content.append(
  2049. this.info_template({
  2050. 'message': __('Topic set by %1$s to: %2$s', sender, subject)
  2051. }));
  2052. }
  2053. if (!body) { return true; }
  2054. this.showMessage($chat_content,
  2055. {'message': body,
  2056. 'sender': sender === this.model.get('nick') && 'me' || 'room',
  2057. 'fullname': sender,
  2058. 'time': converse.toISOString(message_datetime)
  2059. });
  2060. return true;
  2061. },
  2062. occupant_template: _.template(
  2063. '<li class="{{role}}" '+
  2064. '{[ if (role === "moderator") { ]}' +
  2065. 'title="'+__('This user is a moderator')+'"' +
  2066. '{[ } ]}'+
  2067. '{[ if (role === "participant") { ]}' +
  2068. 'title="'+__('This user can send messages in this room')+'"' +
  2069. '{[ } ]}'+
  2070. '{[ if (role === "visitor") { ]}' +
  2071. 'title="'+__('This user can NOT send messages in this room')+'"' +
  2072. '{[ } ]}'+
  2073. '>{{nick}}</li>'
  2074. ),
  2075. onChatRoomRoster: function (roster, room) {
  2076. this.renderChatArea();
  2077. var controlboxview = converse.chatboxesview.views.controlbox,
  2078. roster_size = _.size(roster),
  2079. $participant_list = this.$el.find('.participant-list'),
  2080. participants = [], keys = _.keys(roster), i;
  2081. this.$el.find('.participant-list').empty();
  2082. for (i=0; i<roster_size; i++) {
  2083. participants.push(
  2084. this.occupant_template({
  2085. role: roster[keys[i]].role,
  2086. nick: Strophe.unescapeNode(keys[i])
  2087. }));
  2088. }
  2089. $participant_list.append(participants.join(""));
  2090. return true;
  2091. }
  2092. });
  2093. this.ChatBoxes = Backbone.Collection.extend({
  2094. model: converse.ChatBox,
  2095. onConnected: function () {
  2096. this.localStorage = new Backbone.LocalStorage(
  2097. hex_sha1('converse.chatboxes-'+converse.bare_jid));
  2098. if (!this.get('controlbox')) {
  2099. this.add({
  2100. id: 'controlbox',
  2101. box_id: 'controlbox'
  2102. });
  2103. } else {
  2104. this.get('controlbox').save();
  2105. }
  2106. // This will make sure the Roster is set up
  2107. this.get('controlbox').set({connected:true});
  2108. // Register message handler
  2109. converse.connection.addHandler(
  2110. $.proxy(function (message) {
  2111. this.messageReceived(message);
  2112. return true;
  2113. }, this), null, 'message', 'chat');
  2114. // Get cached chatboxes from localstorage
  2115. this.fetch({
  2116. add: true,
  2117. success: $.proxy(function (collection, resp) {
  2118. if (_.include(_.pluck(resp, 'id'), 'controlbox')) {
  2119. // If the controlbox was saved in localstorage, it must be visible
  2120. this.get('controlbox').set({visible:true}).save();
  2121. }
  2122. }, this)
  2123. });
  2124. },
  2125. messageReceived: function (message) {
  2126. var partner_jid, $message = $(message),
  2127. message_from = $message.attr('from');
  2128. if (message_from == converse.connection.jid) {
  2129. // FIXME: Forwarded messages should be sent to specific resources,
  2130. // not broadcasted
  2131. return true;
  2132. }
  2133. var $forwarded = $message.children('forwarded');
  2134. if ($forwarded.length) {
  2135. $message = $forwarded.children('message');
  2136. }
  2137. var from = Strophe.getBareJidFromJid(message_from),
  2138. to = Strophe.getBareJidFromJid($message.attr('to')),
  2139. resource, chatbox, roster_item;
  2140. if (from == converse.bare_jid) {
  2141. // I am the sender, so this must be a forwarded message...
  2142. partner_jid = to;
  2143. resource = Strophe.getResourceFromJid($message.attr('to'));
  2144. } else {
  2145. partner_jid = from;
  2146. resource = Strophe.getResourceFromJid(message_from);
  2147. }
  2148. chatbox = this.get(partner_jid);
  2149. roster_item = converse.roster.get(partner_jid);
  2150. if (roster_item === undefined) {
  2151. // The buddy was likely removed
  2152. converse.log('Could not get roster item for JID '+partner_jid, 'error');
  2153. return true;
  2154. }
  2155. if (!chatbox) {
  2156. chatbox = this.create({
  2157. 'id': partner_jid,
  2158. 'jid': partner_jid,
  2159. 'fullname': roster_item.get('fullname') || jid,
  2160. 'image_type': roster_item.get('image_type'),
  2161. 'image': roster_item.get('image'),
  2162. 'url': roster_item.get('url')
  2163. });
  2164. }
  2165. chatbox.messageReceived(message);
  2166. converse.roster.addResource(partner_jid, resource);
  2167. return true;
  2168. }
  2169. });
  2170. this.ChatBoxesView = Backbone.View.extend({
  2171. el: '#chatpanel',
  2172. initialize: function () {
  2173. // boxesviewinit
  2174. this.views = {};
  2175. this.model.on("add", function (item) {
  2176. var view = this.views[item.get('id')];
  2177. if (!view) {
  2178. if (item.get('chatroom')) {
  2179. view = new converse.ChatRoomView({'model': item});
  2180. } else if (item.get('box_id') === 'controlbox') {
  2181. view = new converse.ControlBoxView({model: item});
  2182. view.render();
  2183. } else {
  2184. view = new converse.ChatBoxView({model: item});
  2185. }
  2186. this.views[item.get('id')] = view;
  2187. } else {
  2188. delete view.model; // Remove ref to old model to help garbage collection
  2189. view.model = item;
  2190. view.initialize();
  2191. if (item.get('id') !== 'controlbox') {
  2192. // FIXME: Why is it necessary to again append chatboxes?
  2193. view.$el.appendTo(this.$el);
  2194. }
  2195. }
  2196. }, this);
  2197. },
  2198. showChatBox: function (attrs) {
  2199. var chatbox = this.model.get(attrs.jid);
  2200. if (chatbox) {
  2201. chatbox.trigger('show');
  2202. } else {
  2203. chatbox = this.model.create(attrs, {
  2204. 'error': function (model, response) {
  2205. converse.log(response.responseText);
  2206. }
  2207. });
  2208. }
  2209. return chatbox;
  2210. }
  2211. });
  2212. this.RosterItem = Backbone.Model.extend({
  2213. initialize: function (attributes, options) {
  2214. var jid = attributes.jid;
  2215. if (!attributes.fullname) {
  2216. attributes.fullname = jid;
  2217. }
  2218. var attrs = _.extend({
  2219. 'id': jid,
  2220. 'user_id': Strophe.getNodeFromJid(jid),
  2221. 'resources': [],
  2222. 'status': ''
  2223. }, attributes);
  2224. attrs.sorted = false;
  2225. attrs.chat_status = 'offline';
  2226. this.set(attrs);
  2227. }
  2228. });
  2229. this.RosterItemView = Backbone.View.extend({
  2230. tagName: 'dd',
  2231. events: {
  2232. "click .accept-xmpp-request": "acceptRequest",
  2233. "click .decline-xmpp-request": "declineRequest",
  2234. "click .open-chat": "openChat",
  2235. "click .remove-xmpp-contact": "removeContact"
  2236. },
  2237. openChat: function (ev) {
  2238. ev.preventDefault();
  2239. converse.chatboxesview.showChatBox({
  2240. 'id': this.model.get('jid'),
  2241. 'jid': this.model.get('jid'),
  2242. 'fullname': this.model.get('fullname'),
  2243. 'image_type': this.model.get('image_type'),
  2244. 'image': this.model.get('image'),
  2245. 'url': this.model.get('url'),
  2246. 'status': this.model.get('status')
  2247. });
  2248. },
  2249. removeContact: function (ev) {
  2250. ev.preventDefault();
  2251. var result = confirm("Are you sure you want to remove this contact?");
  2252. if (result === true) {
  2253. var bare_jid = this.model.get('jid');
  2254. converse.connection.roster.remove(bare_jid, function (iq) {
  2255. converse.connection.roster.unauthorize(bare_jid);
  2256. converse.rosterview.model.remove(bare_jid);
  2257. });
  2258. }
  2259. },
  2260. acceptRequest: function (ev) {
  2261. var jid = this.model.get('jid');
  2262. converse.connection.roster.authorize(jid);
  2263. converse.connection.roster.add(jid, this.model.get('fullname'), [], function (iq) {
  2264. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  2265. });
  2266. ev.preventDefault();
  2267. },
  2268. declineRequest: function (ev) {
  2269. ev.preventDefault();
  2270. converse.connection.roster.unauthorize(this.model.get('jid'));
  2271. this.model.destroy();
  2272. },
  2273. template: _.template(
  2274. '<a class="open-chat" title="'+__('Click to chat with this contact')+'" href="#">'+
  2275. '<span class="icon-{{ chat_status }}" title="{{ status_desc }}"></span>{{ fullname }}'+
  2276. '</a>' +
  2277. '<a class="remove-xmpp-contact icon-remove" title="'+__('Click to remove this contact')+'" href="#"></a>'),
  2278. pending_template: _.template(
  2279. '<span>{{ fullname }}</span>' +
  2280. '<a class="remove-xmpp-contact icon-remove" title="'+__('Click to remove this contact')+'" href="#"></a>'),
  2281. request_template: _.template('<div>{{ fullname }}</div>' +
  2282. '<button type="button" class="accept-xmpp-request">' +
  2283. 'Accept</button>' +
  2284. '<button type="button" class="decline-xmpp-request">' +
  2285. 'Decline</button>' +
  2286. ''),
  2287. render: function () {
  2288. var item = this.model,
  2289. ask = item.get('ask'),
  2290. subscription = item.get('subscription');
  2291. var classes_to_remove = [
  2292. 'current-xmpp-contact',
  2293. 'pending-xmpp-contact',
  2294. 'requesting-xmpp-contact'
  2295. ].concat(_.keys(STATUSES));
  2296. _.each(classes_to_remove,
  2297. function (cls) {
  2298. if (this.el.className.indexOf(cls) !== -1) {
  2299. this.$el.removeClass(cls);
  2300. }
  2301. }, this);
  2302. this.$el.addClass(item.get('chat_status'));
  2303. if (ask === 'subscribe') {
  2304. this.$el.addClass('pending-xmpp-contact');
  2305. this.$el.html(this.pending_template(item.toJSON()));
  2306. } else if (ask === 'request') {
  2307. this.$el.addClass('requesting-xmpp-contact');
  2308. this.$el.html(this.request_template(item.toJSON()));
  2309. converse.showControlBox();
  2310. } else if (subscription === 'both' || subscription === 'to') {
  2311. this.$el.addClass('current-xmpp-contact');
  2312. this.$el.html(this.template(
  2313. _.extend(item.toJSON(), {'status_desc': STATUSES[item.get('chat_status')||'offline']})
  2314. ));
  2315. }
  2316. return this;
  2317. }
  2318. });
  2319. this.RosterItems = Backbone.Collection.extend({
  2320. model: converse.RosterItem,
  2321. comparator : function (rosteritem) {
  2322. var chat_status = rosteritem.get('chat_status'),
  2323. rank = 4;
  2324. switch(chat_status) {
  2325. case 'offline':
  2326. rank = 0;
  2327. break;
  2328. case 'unavailable':
  2329. rank = 1;
  2330. break;
  2331. case 'xa':
  2332. rank = 2;
  2333. break;
  2334. case 'away':
  2335. rank = 3;
  2336. break;
  2337. case 'dnd':
  2338. rank = 4;
  2339. break;
  2340. case 'online':
  2341. rank = 5;
  2342. break;
  2343. }
  2344. return rank;
  2345. },
  2346. subscribeToSuggestedItems: function (msg) {
  2347. $(msg).find('item').each(function () {
  2348. var $this = $(this),
  2349. jid = $this.attr('jid'),
  2350. action = $this.attr('action'),
  2351. fullname = $this.attr('name');
  2352. if (action === 'add') {
  2353. converse.connection.roster.add(jid, fullname, [], function (iq) {
  2354. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  2355. });
  2356. }
  2357. });
  2358. return true;
  2359. },
  2360. isSelf: function (jid) {
  2361. return (Strophe.getBareJidFromJid(jid) === Strophe.getBareJidFromJid(converse.connection.jid));
  2362. },
  2363. addResource: function (bare_jid, resource) {
  2364. var item = this.get(bare_jid),
  2365. resources;
  2366. if (item) {
  2367. resources = item.get('resources');
  2368. if (resources) {
  2369. if (_.indexOf(resources, resource) == -1) {
  2370. resources.push(resource);
  2371. item.set({'resources': resources});
  2372. }
  2373. } else {
  2374. item.set({'resources': [resource]});
  2375. }
  2376. }
  2377. },
  2378. removeResource: function (bare_jid, resource) {
  2379. var item = this.get(bare_jid),
  2380. resources,
  2381. idx;
  2382. if (item) {
  2383. resources = item.get('resources');
  2384. idx = _.indexOf(resources, resource);
  2385. if (idx !== -1) {
  2386. resources.splice(idx, 1);
  2387. item.set({'resources': resources});
  2388. return resources.length;
  2389. }
  2390. }
  2391. return 0;
  2392. },
  2393. subscribeBack: function (jid) {
  2394. var bare_jid = Strophe.getBareJidFromJid(jid);
  2395. if (converse.connection.roster.findItem(bare_jid)) {
  2396. converse.connection.roster.authorize(bare_jid);
  2397. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  2398. } else {
  2399. converse.connection.roster.add(jid, '', [], function (iq) {
  2400. converse.connection.roster.authorize(bare_jid);
  2401. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  2402. });
  2403. }
  2404. },
  2405. unsubscribe: function (jid) {
  2406. /* Upon receiving the presence stanza of type "unsubscribed",
  2407. * the user SHOULD acknowledge receipt of that subscription state
  2408. * notification by sending a presence stanza of type "unsubscribe"
  2409. * this step lets the user's server know that it MUST no longer
  2410. * send notification of the subscription state change to the user.
  2411. */
  2412. converse.xmppstatus.sendPresence('unsubscribe');
  2413. if (converse.connection.roster.findItem(jid)) {
  2414. converse.connection.roster.remove(jid, function (iq) {
  2415. converse.rosterview.model.remove(jid);
  2416. });
  2417. }
  2418. },
  2419. getNumOnlineContacts: function () {
  2420. var count = 0,
  2421. models = this.models,
  2422. models_length = models.length,
  2423. i;
  2424. for (i=0; i<models_length; i++) {
  2425. if (_.indexOf(['offline', 'unavailable'], models[i].get('chat_status')) === -1) {
  2426. count++;
  2427. }
  2428. }
  2429. return count;
  2430. },
  2431. cleanCache: function (items) {
  2432. /* The localstorage cache containing roster contacts might contain
  2433. * some contacts that aren't actually in our roster anymore. We
  2434. * therefore need to remove them now.
  2435. */
  2436. var id, i,
  2437. roster_ids = [];
  2438. for (i=0; i < items.length; ++i) {
  2439. roster_ids.push(items[i].jid);
  2440. }
  2441. for (i=0; i < this.models.length; ++i) {
  2442. id = this.models[i].get('id');
  2443. if (_.indexOf(roster_ids, id) === -1) {
  2444. this.get(id).destroy();
  2445. }
  2446. }
  2447. },
  2448. rosterHandler: function (items) {
  2449. this.cleanCache(items);
  2450. _.each(items, function (item, index, items) {
  2451. if (this.isSelf(item.jid)) { return; }
  2452. var model = this.get(item.jid);
  2453. if (!model) {
  2454. if ((item.subscription === 'none') && (item.ask === null)) {
  2455. // We're not interested in zombies
  2456. return;
  2457. }
  2458. is_last = false;
  2459. if (index === (items.length-1)) { is_last = true; }
  2460. this.create({
  2461. jid: item.jid,
  2462. subscription: item.subscription,
  2463. ask: item.ask,
  2464. fullname: item.name || item.jid,
  2465. is_last: is_last
  2466. });
  2467. } else {
  2468. if ((item.subscription === 'none') && (item.ask === null)) {
  2469. // This user is no longer in our roster
  2470. model.destroy();
  2471. } else if (model.get('subscription') !== item.subscription || model.get('ask') !== item.ask) {
  2472. // only modify model attributes if they are different from the
  2473. // ones that were already set when the rosterItem was added
  2474. model.set({'subscription': item.subscription, 'ask': item.ask});
  2475. model.save();
  2476. }
  2477. }
  2478. }, this);
  2479. if (!converse.initial_presence_sent) {
  2480. /* Once we've sent out our initial presence stanza, we'll
  2481. * start receiving presence stanzas from our contacts.
  2482. * We therefore only want to do this after our roster has
  2483. * been set up (otherwise we can't meaningfully process
  2484. * incoming presence stanzas).
  2485. */
  2486. converse.initial_presence_sent = 1;
  2487. converse.xmppstatus.sendPresence();
  2488. }
  2489. },
  2490. handleIncomingSubscription: function (jid) {
  2491. var bare_jid = Strophe.getBareJidFromJid(jid);
  2492. var item = this.get(bare_jid);
  2493. if (!converse.allow_contact_requests) {
  2494. converse.connection.roster.unauthorize(bare_jid);
  2495. return true;
  2496. }
  2497. if (converse.auto_subscribe) {
  2498. if ((!item) || (item.get('subscription') != 'to')) {
  2499. this.subscribeBack(jid);
  2500. } else {
  2501. converse.connection.roster.authorize(bare_jid);
  2502. }
  2503. } else {
  2504. if ((item) && (item.get('subscription') != 'none')) {
  2505. converse.connection.roster.authorize(bare_jid);
  2506. } else {
  2507. if (!this.get(bare_jid)) {
  2508. converse.getVCard(
  2509. bare_jid,
  2510. $.proxy(function (jid, fullname, img, img_type, url) {
  2511. this.add({
  2512. jid: bare_jid,
  2513. subscription: 'none',
  2514. ask: 'request',
  2515. fullname: fullname,
  2516. image: img,
  2517. image_type: img_type,
  2518. url: url,
  2519. vcard_updated: converse.toISOString(new Date()),
  2520. is_last: true
  2521. });
  2522. }, this),
  2523. $.proxy(function (jid, fullname, img, img_type, url) {
  2524. converse.log("Error while retrieving vcard");
  2525. // XXX: Should vcard_updated be set here as
  2526. // well?
  2527. this.add({jid: bare_jid, subscription: 'none', ask: 'request', fullname: jid, is_last: true});
  2528. }, this)
  2529. );
  2530. } else {
  2531. return true;
  2532. }
  2533. }
  2534. }
  2535. return true;
  2536. },
  2537. presenceHandler: function (presence) {
  2538. var $presence = $(presence),
  2539. presence_type = $presence.attr('type');
  2540. if (presence_type === 'error') {
  2541. // TODO
  2542. // error presence stanzas don't necessarily have a 'from' attr.
  2543. return true;
  2544. }
  2545. var jid = $presence.attr('from'),
  2546. bare_jid = Strophe.getBareJidFromJid(jid),
  2547. resource = Strophe.getResourceFromJid(jid),
  2548. $show = $presence.find('show'),
  2549. chat_status = $show.text() || 'online',
  2550. status_message = $presence.find('status'),
  2551. item;
  2552. if (this.isSelf(bare_jid)) {
  2553. if ((converse.connection.jid !== jid)&&(presence_type !== 'unavailable')) {
  2554. // Another resource has changed it's status, we'll update ours as well.
  2555. // FIXME: We should ideally differentiate between converse.js using
  2556. // resources and other resources (i.e Pidgin etc.)
  2557. converse.xmppstatus.save({'status': chat_status});
  2558. }
  2559. return true;
  2560. } else if (($presence.find('x').attr('xmlns') || '').indexOf(Strophe.NS.MUC) === 0) {
  2561. return true; // Ignore MUC
  2562. }
  2563. item = this.get(bare_jid);
  2564. if (item && (status_message.text() != item.get('status'))) {
  2565. item.save({'status': status_message.text()});
  2566. }
  2567. if ((presence_type === 'subscribed') || (presence_type === 'unsubscribe')) {
  2568. return true;
  2569. } else if (presence_type === 'subscribe') {
  2570. return this.handleIncomingSubscription(jid);
  2571. } else if (presence_type === 'unsubscribed') {
  2572. this.unsubscribe(bare_jid);
  2573. } else if (presence_type === 'unavailable') {
  2574. if (this.removeResource(bare_jid, resource) === 0) {
  2575. if (item) {
  2576. item.set({'chat_status': 'offline'});
  2577. }
  2578. }
  2579. } else if (item) {
  2580. // presence_type is undefined
  2581. this.addResource(bare_jid, resource);
  2582. item.set({'chat_status': chat_status});
  2583. }
  2584. return true;
  2585. }
  2586. });
  2587. this.RosterView = Backbone.View.extend({
  2588. tagName: 'dl',
  2589. id: 'converse-roster',
  2590. rosteritemviews: {},
  2591. requesting_contacts_template: _.template(
  2592. '<dt id="xmpp-contact-requests">'+__('Contact requests')+'</dt>'),
  2593. contacts_template: _.template(
  2594. '<dt id="xmpp-contacts">'+__('My contacts')+'</dt>'),
  2595. pending_contacts_template: _.template(
  2596. '<dt id="pending-xmpp-contacts">'+__('Pending contacts')+'</dt>'),
  2597. initialize: function () {
  2598. this.model.on("add", function (item) {
  2599. this.addRosterItemView(item).render(item);
  2600. if (!item.get('vcard_updated')) {
  2601. // This will update the vcard, which triggers a change
  2602. // request which will rerender the roster item.
  2603. converse.getVCard(item.get('jid'));
  2604. }
  2605. }, this);
  2606. this.model.on('change', function (item) {
  2607. if ((_.size(item.changed) === 1) && _.contains(_.keys(item.changed), 'sorted')) {
  2608. return;
  2609. }
  2610. this.updateChatBox(item).render(item);
  2611. }, this);
  2612. this.model.on("remove", function (item) { this.removeRosterItemView(item); }, this);
  2613. this.model.on("destroy", function (item) { this.removeRosterItemView(item); }, this);
  2614. var roster_markup = this.contacts_template();
  2615. if (converse.allow_contact_requests) {
  2616. roster_markup = this.requesting_contacts_template() + roster_markup + this.pending_contacts_template();
  2617. }
  2618. this.$el.hide().html(roster_markup);
  2619. this.model.fetch({add: true}); // Get the cached roster items from localstorage
  2620. },
  2621. updateChatBox: function (item, changed) {
  2622. var chatbox = converse.chatboxes.get(item.get('jid')),
  2623. changes = {};
  2624. if (!chatbox) {
  2625. return this;
  2626. }
  2627. if (_.has(item.changed, 'chat_status')) {
  2628. changes.chat_status = item.get('chat_status');
  2629. }
  2630. if (_.has(item.changed, 'status')) {
  2631. changes.status = item.get('status');
  2632. }
  2633. chatbox.save(changes);
  2634. return this;
  2635. },
  2636. addRosterItemView: function (item) {
  2637. var view = new converse.RosterItemView({model: item});
  2638. this.rosteritemviews[item.id] = view;
  2639. return this;
  2640. },
  2641. removeRosterItemView: function (item) {
  2642. var view = this.rosteritemviews[item.id];
  2643. if (view) {
  2644. view.$el.remove();
  2645. delete this.rosteritemviews[item.id];
  2646. this.render();
  2647. }
  2648. return this;
  2649. },
  2650. renderRosterItem: function (item, view) {
  2651. if ((converse.show_only_online_users) && (item.get('chat_status') !== 'online')) {
  2652. view.$el.remove();
  2653. view.delegateEvents();
  2654. return this;
  2655. }
  2656. if ($.contains(document.documentElement, view.el)) {
  2657. view.render();
  2658. } else {
  2659. this.$el.find('#xmpp-contacts').after(view.render().el);
  2660. }
  2661. },
  2662. render: function (item) {
  2663. var $my_contacts = this.$el.find('#xmpp-contacts'),
  2664. $contact_requests = this.$el.find('#xmpp-contact-requests'),
  2665. $pending_contacts = this.$el.find('#pending-xmpp-contacts'),
  2666. sorted = false,
  2667. $count, changed_presence;
  2668. if (item) {
  2669. var jid = item.id,
  2670. view = this.rosteritemviews[item.id],
  2671. ask = item.get('ask'),
  2672. subscription = item.get('subscription'),
  2673. crit = {order:'asc'};
  2674. if (ask === 'subscribe') {
  2675. $pending_contacts.after(view.render().el);
  2676. $pending_contacts.after($pending_contacts.siblings('dd.pending-xmpp-contact').tsort(crit));
  2677. } else if (ask === 'request') {
  2678. $contact_requests.after(view.render().el);
  2679. $contact_requests.after($contact_requests.siblings('dd.requesting-xmpp-contact').tsort(crit));
  2680. } else if (subscription === 'both' || subscription === 'to') {
  2681. this.renderRosterItem(item, view);
  2682. }
  2683. changed_presence = item.changed.chat_status;
  2684. if (changed_presence) {
  2685. this.sortRoster(changed_presence);
  2686. sorted = true;
  2687. }
  2688. if (item.get('is_last')) {
  2689. if (!sorted) {
  2690. this.sortRoster(item.get('chat_status'));
  2691. }
  2692. if (!this.$el.is(':visible')) {
  2693. // Once all initial roster items have been added, we
  2694. // can show the roster.
  2695. this.$el.show();
  2696. }
  2697. }
  2698. }
  2699. // Hide the headings if there are no contacts under them
  2700. _.each([$my_contacts, $contact_requests, $pending_contacts], function (h) {
  2701. if (h.nextUntil('dt').length) {
  2702. if (!h.is(':visible')) {
  2703. h.show();
  2704. }
  2705. }
  2706. else if (h.is(':visible')) {
  2707. h.hide();
  2708. }
  2709. });
  2710. $count = $('#online-count');
  2711. $count.text('('+this.model.getNumOnlineContacts()+')');
  2712. if (!$count.is(':visible')) {
  2713. $count.show();
  2714. }
  2715. return this;
  2716. },
  2717. sortRoster: function (chat_status) {
  2718. var $my_contacts = this.$el.find('#xmpp-contacts');
  2719. $my_contacts.siblings('dd.current-xmpp-contact.'+chat_status).tsort('a', {order:'asc'});
  2720. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.offline'));
  2721. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.unavailable'));
  2722. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.xa'));
  2723. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.away'));
  2724. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.dnd'));
  2725. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.online'));
  2726. }
  2727. });
  2728. this.XMPPStatus = Backbone.Model.extend({
  2729. initialize: function () {
  2730. this.set({
  2731. 'status' : this.get('status') || 'online'
  2732. });
  2733. this.on('change', $.proxy(function () {
  2734. if (this.get('fullname') === undefined) {
  2735. converse.getVCard(
  2736. null, // No 'to' attr when getting one's own vCard
  2737. $.proxy(function (jid, fullname, image, image_type, url) {
  2738. this.save({'fullname': fullname});
  2739. }, this)
  2740. );
  2741. }
  2742. }, this));
  2743. },
  2744. sendPresence: function (type) {
  2745. if (type === undefined) {
  2746. type = this.get('status') || 'online';
  2747. }
  2748. var status_message = this.get('status_message'),
  2749. presence;
  2750. // Most of these presence types are actually not explicitly sent,
  2751. // but I add all of them here fore reference and future proofing.
  2752. if ((type === 'unavailable') ||
  2753. (type === 'probe') ||
  2754. (type === 'error') ||
  2755. (type === 'unsubscribe') ||
  2756. (type === 'unsubscribed') ||
  2757. (type === 'subscribe') ||
  2758. (type === 'subscribed')) {
  2759. presence = $pres({'type':type});
  2760. } else {
  2761. if (type === 'online') {
  2762. presence = $pres();
  2763. } else {
  2764. presence = $pres().c('show').t(type).up();
  2765. }
  2766. if (status_message) {
  2767. presence.c('status').t(status_message);
  2768. }
  2769. }
  2770. converse.connection.send(presence);
  2771. },
  2772. setStatus: function (value) {
  2773. this.sendPresence(value);
  2774. this.save({'status': value});
  2775. },
  2776. setStatusMessage: function (status_message) {
  2777. converse.connection.send($pres().c('show').t(this.get('status')).up().c('status').t(status_message));
  2778. this.save({'status_message': status_message});
  2779. if (this.xhr_custom_status) {
  2780. $.ajax({
  2781. url: 'set-custom-status',
  2782. type: 'POST',
  2783. data: {'msg': status_message}
  2784. });
  2785. }
  2786. }
  2787. });
  2788. this.XMPPStatusView = Backbone.View.extend({
  2789. el: "span#xmpp-status-holder",
  2790. events: {
  2791. "click a.choose-xmpp-status": "toggleOptions",
  2792. "click #fancy-xmpp-status-select a.change-xmpp-status-message": "renderStatusChangeForm",
  2793. "submit #set-custom-xmpp-status": "setStatusMessage",
  2794. "click .dropdown dd ul li a": "setStatus"
  2795. },
  2796. toggleOptions: function (ev) {
  2797. ev.preventDefault();
  2798. $(ev.target).parent().parent().siblings('dd').find('ul').toggle('fast');
  2799. },
  2800. change_status_message_template: _.template(
  2801. '<form id="set-custom-xmpp-status">' +
  2802. '<input type="text" class="custom-xmpp-status" {{ status_message }}"'+
  2803. 'placeholder="'+__('Custom status')+'"/>' +
  2804. '<button type="submit">'+__('Save')+'</button>' +
  2805. '</form>'),
  2806. status_template: _.template(
  2807. '<div class="xmpp-status">' +
  2808. '<a class="choose-xmpp-status {{ chat_status }}" data-value="{{status_message}}" href="#" title="'+__('Click to change your chat status')+'">' +
  2809. '<span class="icon-{{ chat_status }}"></span>'+
  2810. '{{ status_message }}' +
  2811. '</a>' +
  2812. '<a class="change-xmpp-status-message icon-pencil" href="#" title="'+__('Click here to write a custom status message')+'"></a>' +
  2813. '</div>'),
  2814. renderStatusChangeForm: function (ev) {
  2815. ev.preventDefault();
  2816. var status_message = this.model.get('status') || 'offline';
  2817. var input = this.change_status_message_template({'status_message': status_message});
  2818. this.$el.find('.xmpp-status').replaceWith(input);
  2819. this.$el.find('.custom-xmpp-status').focus().focus();
  2820. },
  2821. setStatusMessage: function (ev) {
  2822. ev.preventDefault();
  2823. var status_message = $(ev.target).find('input').val();
  2824. if (status_message === "") {
  2825. }
  2826. this.model.setStatusMessage(status_message);
  2827. },
  2828. setStatus: function (ev) {
  2829. ev.preventDefault();
  2830. var $el = $(ev.target),
  2831. value = $el.attr('data-value');
  2832. this.model.setStatus(value);
  2833. this.$el.find(".dropdown dd ul").hide();
  2834. },
  2835. getPrettyStatus: function (stat) {
  2836. if (stat === 'chat') {
  2837. pretty_status = __('online');
  2838. } else if (stat === 'dnd') {
  2839. pretty_status = __('busy');
  2840. } else if (stat === 'xa') {
  2841. pretty_status = __('away for long');
  2842. } else if (stat === 'away') {
  2843. pretty_status = __('away');
  2844. } else {
  2845. pretty_status = __(stat) || __('online'); // XXX: Is 'online' the right default choice here?
  2846. }
  2847. return pretty_status;
  2848. },
  2849. updateStatusUI: function (model) {
  2850. if (!(_.has(model.changed, 'status')) && !(_.has(model.changed, 'status_message'))) {
  2851. return;
  2852. }
  2853. var stat = model.get('status');
  2854. // # For translators: the %1$s part gets replaced with the status
  2855. // # Example, I am online
  2856. var status_message = model.get('status_message') || __("I am %1$s", this.getPrettyStatus(stat));
  2857. this.$el.find('#fancy-xmpp-status-select').html(
  2858. this.status_template({
  2859. 'chat_status': stat,
  2860. 'status_message': status_message
  2861. }));
  2862. },
  2863. choose_template: _.template(
  2864. '<dl id="target" class="dropdown">' +
  2865. '<dt id="fancy-xmpp-status-select" class="fancy-dropdown"></dt>' +
  2866. '<dd><ul class="xmpp-status-menu"></ul></dd>' +
  2867. '</dl>'),
  2868. option_template: _.template(
  2869. '<li>' +
  2870. '<a href="#" class="{{ value }}" data-value="{{ value }}">'+
  2871. '<span class="icon-{{ value }}"></span>'+
  2872. '{{ text }}'+
  2873. '</a>' +
  2874. '</li>'),
  2875. initialize: function () {
  2876. this.model.on("change", this.updateStatusUI, this);
  2877. },
  2878. render: function () {
  2879. // Replace the default dropdown with something nicer
  2880. var $select = this.$el.find('select#select-xmpp-status'),
  2881. chat_status = this.model.get('status') || 'offline',
  2882. options = $('option', $select),
  2883. $options_target,
  2884. options_list = [],
  2885. that = this;
  2886. this.$el.html(this.choose_template());
  2887. this.$el.find('#fancy-xmpp-status-select')
  2888. .html(this.status_template({
  2889. 'status_message': this.model.get('status_message') || __("I am %1$s", this.getPrettyStatus(chat_status)),
  2890. 'chat_status': chat_status
  2891. }));
  2892. // iterate through all the <option> elements and add option values
  2893. options.each(function(){
  2894. options_list.push(that.option_template({'value': $(this).val(),
  2895. 'text': this.text
  2896. }));
  2897. });
  2898. $options_target = this.$el.find("#target dd ul").hide();
  2899. $options_target.append(options_list.join(''));
  2900. $select.remove();
  2901. return this;
  2902. }
  2903. });
  2904. this.Feature = Backbone.Model.extend();
  2905. this.Features = Backbone.Collection.extend({
  2906. /* Service Discovery
  2907. * -----------------
  2908. * This collection stores Feature Models, representing features
  2909. * provided by available XMPP entities (e.g. servers)
  2910. * See XEP-0030 for more details: http://xmpp.org/extensions/xep-0030.html
  2911. * All features are shown here: http://xmpp.org/registrar/disco-features.html
  2912. */
  2913. model: converse.Feature,
  2914. initialize: function () {
  2915. this.localStorage = new Backbone.LocalStorage(
  2916. hex_sha1('converse.features'+converse.bare_jid));
  2917. if (this.localStorage.records.length === 0) {
  2918. // localStorage is empty, so we've likely never queried this
  2919. // domain for features yet
  2920. converse.connection.disco.info(converse.domain, null, $.proxy(this.onInfo, this));
  2921. converse.connection.disco.items(converse.domain, null, $.proxy(this.onItems, this));
  2922. } else {
  2923. this.fetch({add:true});
  2924. }
  2925. },
  2926. onItems: function (stanza) {
  2927. $(stanza).find('query item').each($.proxy(function (idx, item) {
  2928. converse.connection.disco.info(
  2929. $(item).attr('jid'),
  2930. null,
  2931. $.proxy(this.onInfo, this));
  2932. }, this));
  2933. },
  2934. onInfo: function (stanza) {
  2935. var $stanza = $(stanza);
  2936. if (($stanza.find('identity[category=server][type=im]').length === 0) &&
  2937. ($stanza.find('identity[category=conference][type=text]').length === 0)) {
  2938. // This isn't an IM server component
  2939. return;
  2940. }
  2941. $stanza.find('feature').each($.proxy(function (idx, feature) {
  2942. this.create({
  2943. 'var': $(feature).attr('var'),
  2944. 'from': $stanza.attr('from')
  2945. });
  2946. }, this));
  2947. }
  2948. });
  2949. this.LoginPanel = Backbone.View.extend({
  2950. tagName: 'div',
  2951. id: "login-dialog",
  2952. events: {
  2953. 'submit form#converse-login': 'authenticate'
  2954. },
  2955. tab_template: _.template(
  2956. '<li><a class="current" href="#login">'+__('Sign in')+'</a></li>'),
  2957. template: _.template(
  2958. '<form id="converse-login">' +
  2959. '<label>'+__('XMPP/Jabber Username:')+'</label>' +
  2960. '<input type="username" name="jid">' +
  2961. '<label>'+__('Password:')+'</label>' +
  2962. '<input type="password" name="password">' +
  2963. '<input class="login-submit" type="submit" value="'+__('Log In')+'">' +
  2964. '</form">'),
  2965. bosh_url_input: _.template(
  2966. '<label>'+__('BOSH Service URL:')+'</label>' +
  2967. '<input type="text" id="bosh_service_url">'),
  2968. connect: function ($form, jid, password) {
  2969. if ($form) {
  2970. $form.find('input[type=submit]').hide().after('<span class="spinner login-submit"/>');
  2971. }
  2972. converse.connection = new Strophe.Connection(converse.bosh_service_url);
  2973. converse.connection.connect(jid, password, converse.onConnect);
  2974. },
  2975. showConnectButton: function () {
  2976. var $form = this.$el.find('#converse-login');
  2977. var $button = $form.find('input[type=submit]');
  2978. if ($button.length) {
  2979. $button.show().siblings('span').remove();
  2980. }
  2981. },
  2982. initialize: function (cfg) {
  2983. cfg.$parent.html(this.$el.html(this.template()));
  2984. this.$tabs = cfg.$parent.parent().find('#controlbox-tabs');
  2985. this.model.on('connection-fail', function () { this.showConnectButton(); }, this);
  2986. this.model.on('auth-fail', function () { this.showConnectButton(); }, this);
  2987. },
  2988. render: function () {
  2989. this.$tabs.append(this.tab_template());
  2990. this.$el.find('input#jid').focus();
  2991. return this;
  2992. },
  2993. authenticate: function (ev) {
  2994. var $form = $(ev.target),
  2995. $jid_input = $form.find('input[name=jid]'),
  2996. jid = $jid_input.val(),
  2997. $pw_input = $form.find('input[name=password]'),
  2998. password = $pw_input.val(),
  2999. $bsu_input = null,
  3000. errors = false;
  3001. if (! converse.bosh_service_url) {
  3002. $bsu_input = $form.find('input#bosh_service_url');
  3003. converse.bosh_service_url = $bsu_input.val();
  3004. if (! converse.bosh_service_url) {
  3005. errors = true;
  3006. $bsu_input.addClass('error');
  3007. }
  3008. }
  3009. if (! jid) {
  3010. errors = true;
  3011. $jid_input.addClass('error');
  3012. }
  3013. if (! password) {
  3014. errors = true;
  3015. $pw_input.addClass('error');
  3016. }
  3017. if (errors) { return; }
  3018. this.connect($form, jid, password);
  3019. return false;
  3020. },
  3021. remove: function () {
  3022. this.$tabs.empty();
  3023. this.$el.parent().empty();
  3024. }
  3025. });
  3026. // Initialization
  3027. // --------------
  3028. // This is the end of the initialize method.
  3029. this.chatboxes = new this.ChatBoxes();
  3030. this.chatboxesview = new this.ChatBoxesView({model: this.chatboxes});
  3031. $('.toggle-online-users').bind(
  3032. 'click',
  3033. $.proxy(function (e) {
  3034. e.preventDefault(); this.toggleControlBox();
  3035. }, this)
  3036. );
  3037. if ((this.prebind) && (!this.connection)) {
  3038. if ((!this.jid) || (!this.sid) || (!this.rid) || (!this.bosh_service_url)) {
  3039. this.log('If you set prebind=true, you MUST supply JID, RID and SID values');
  3040. return;
  3041. }
  3042. this.connection = new Strophe.Connection(this.bosh_service_url);
  3043. this.connection.attach(this.jid, this.sid, this.rid, this.onConnect);
  3044. } else if (this.connection) {
  3045. this.onConnected();
  3046. }
  3047. if (this.show_controlbox_by_default) { this.showControlBox(); }
  3048. };
  3049. return {
  3050. 'initialize': function (settings, callback) {
  3051. converse.initialize(settings, callback);
  3052. }
  3053. };
  3054. }));