duoshuo-ua.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* 多说User-Agent插件
  2. * 作者:Gerald <gera2ld@163.com>
  3. * @require ua-parser.js
  4. */
  5. var UAParser = this.UAParser;
  6. function getUAString(local) {
  7. var agent = UAParser.parse(local.agent);
  8. return '<div class="ds-os">' + UAParser.getString(agent.os) + '</div>' +
  9. '<div class="ds-br">' + UAParser.getString(agent.browser) + '</div>' +
  10. (local.webmaster ? '<div class=ds-webmaster>站长</div>' : '');
  11. }
  12. function callBefore(local, args) {
  13. var myIds = duoshuoQuery.myIds || [];
  14. var e = args[0];
  15. if (args.length == 1) // embed.unstable.js
  16. e = e.post;
  17. local.agent = e.agent;
  18. var id = e.author_id;
  19. if (!myIds.pop) myIds = [myIds];
  20. local.webmaster = myIds.indexOf(id) < 0 ? 0 : id;
  21. }
  22. function callAfter(local, args) {
  23. var res = local.result;
  24. var i = res.indexOf('<div class="ds-comment-header">');
  25. var j = res.indexOf('</div>', i);
  26. var func = duoshuoQuery.getUAString || getUAString;
  27. local.result = res.slice(0, j) + func(local) + res.slice(j);
  28. }
  29. function init() {
  30. var post = DUOSHUO.templates.post;
  31. DUOSHUO.templates.post = function () {
  32. var local = {};
  33. var args = arguments;
  34. callBefore.call(this, local, args);
  35. local.result = post.apply(this, args);
  36. callAfter.call(this, local, args);
  37. return local.result;
  38. }
  39. DUOSHUO.UAParser = UAParser;
  40. }
  41. function observeProperty(item, key, callback) {
  42. function callbackOnce() {
  43. var cb = callback;
  44. if (cb) {
  45. callback = null;
  46. cb();
  47. }
  48. }
  49. var value;
  50. if (item[key]) callbackOnce();
  51. else Object.defineProperty(item, key, {
  52. get: function () {return value;},
  53. set: function (val) {
  54. value = val;
  55. callbackOnce();
  56. },
  57. configurable: true,
  58. });
  59. }
  60. function observePropertyChain(item, keys, callback) {
  61. function observe() {
  62. observeProperty(item, key, function () {
  63. item = item[key];
  64. if(key = keys.shift()) observe();
  65. else callback();
  66. });
  67. }
  68. var key = keys.shift();
  69. observe();
  70. }
  71. observePropertyChain(window, ['DUOSHUO', 'templates', 'post'], init);