index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. var fs = require('fs')
  2. var http = require('http')
  3. var https = require('https')
  4. var path = require('path')
  5. var url = require('url')
  6. var qs = require('querystring')
  7. var FormData = require('form-data')
  8. function NeoCities(user, pass, opts) {
  9. this.user = user
  10. this.pass = pass
  11. this.opts = opts || {}
  12. this.url = url.parse(this.opts.url || 'https://neocities.org')
  13. this.client = this.url.protocol == 'https:' ? https : http
  14. }
  15. NeoCities.prototype.get = function(method, args, callback) {
  16. var path = '/api/'+method
  17. if(args)
  18. path += '?'+qs.stringify(args)
  19. var request = this.client.request({
  20. method: 'get',
  21. host: this.url.hostname,
  22. port: this.url.port,
  23. path: path,
  24. auth: this.user+':'+this.pass
  25. }, function(res) {
  26. var body = ''
  27. res.on('data', function (chunk) {
  28. body += chunk
  29. })
  30. res.on('end', function() {
  31. var resObj = JSON.parse(body)
  32. callback(resObj)
  33. })
  34. })
  35. request.end()
  36. }
  37. NeoCities.prototype.info = function(sitename, callback) {
  38. var args = null
  39. if(typeof sitename == 'function')
  40. callback = sitename
  41. else if(typeof sitename == 'string')
  42. args = {sitename: sitename}
  43. this.get('info', args, callback)
  44. }
  45. NeoCities.prototype.post = function(method, args, callback) {
  46. var form = new FormData()
  47. var i
  48. for(i=0;i<args.length;i++)
  49. form.append(args[i].name, args[i].value)
  50. var request = this.client.request({
  51. method: 'post',
  52. host: this.url.hostname,
  53. port: this.url.port,
  54. path: '/api/'+method,
  55. headers: form.getHeaders(),
  56. auth: this.user+':'+this.pass
  57. }, function(res) {
  58. var body = ''
  59. res.on('data', function (chunk) {
  60. body += chunk
  61. })
  62. res.on('end', function() {
  63. var resObj = JSON.parse(body)
  64. callback(resObj)
  65. })
  66. })
  67. form.pipe(request)
  68. }
  69. NeoCities.prototype.delete = function(filenames, callback) {
  70. var args = []
  71. var i
  72. for(i=0;i<filenames.length;i++)
  73. args.push({name: 'filenames[]', value: filenames[i]})
  74. this.post('delete', args, callback)
  75. }
  76. NeoCities.prototype.upload = function(files, callback) {
  77. var args = []
  78. var i
  79. for(i=0;i<files.length;i++)
  80. args.push({name: files[i].name, value: fs.createReadStream(files[i].path)})
  81. this.post('upload', args, callback)
  82. }
  83. module.exports = NeoCities