Pull out templates logic into its own module

This commit is contained in:
James Allen 2015-02-10 11:24:34 +00:00
parent 6c387edbe2
commit 001a5d751b
12 changed files with 0 additions and 891 deletions

View file

@ -1,93 +0,0 @@
path = require('path')
ProjectUploadManager = require('../Uploads/ProjectUploadManager')
ProjectOptionsHandler = require("../Project/ProjectOptionsHandler")
ProjectDetailsHandler = require('../Project/ProjectDetailsHandler')
ProjectGetter = require('../Project/ProjectGetter')
EditorController = require('../Editor/EditorController')
TemplatesPublisher = require("./TemplatesPublisher")
settings = require('settings-sharelatex')
fs = require('fs')
request = require('request')
uuid = require('node-uuid')
logger = require('logger-sharelatex')
async = require("async")
module.exports =
createProjectFromZipTemplate: (req, res)->
logger.log body:req.session.templateData, "creating project from zip"
if !req.session.templateData?
return res.redirect "/project"
dumpPath = "#{settings.path.dumpFolder}/#{uuid.v4()}"
writeStream = fs.createWriteStream(dumpPath)
zipUrl = req.session.templateData.zipUrl
if zipUrl.slice(0,12).indexOf("templates") == -1
zipUrl = "#{settings.apis.web.url}#{zipUrl}"
else
zipUrl = "#{settings.apis.templates.url}#{zipUrl}"
zipReq = request(zipUrl)
zipReq.on "error", (error) ->
logger.error err: error, "error getting zip from template API"
zipReq.pipe(writeStream)
writeStream.on 'close', ->
ProjectUploadManager.createProjectFromZipArchive req.session.user._id, req.session.templateData.templateName, dumpPath, (err, project)->
if err?
logger.err err:err, zipUrl:zipUrl, "problem building project from zip"
return res.send 500
setCompiler project._id, req.session.templateData.compiler, ->
fs.unlink dumpPath, ->
delete req.session.templateData
res.redirect "/project/#{project._id}"
publishProject: (req, res, next) ->
project_id = req.params.Project_id
ProjectGetter.getProject project_id, {owner_ref: 1}, (error, project) ->
return callback(error) if error?
user_id = project.owner_ref.toString()
logger.log user_id:user_id, project_id:project_id, "receiving request to publish project as template"
TemplatesPublisher.publish user_id, project_id, (error) ->
return next(error) if error?
res.send 204
unpublishProject: (req, res, next) ->
project_id = req.params.Project_id
ProjectGetter.getProject project_id, {owner_ref: 1}, (error, project) ->
return callback(error) if error?
user_id = project.owner_ref.toString()
logger.log user_id:user_id, project_id:project_id, "receiving request to unpublish project"
TemplatesPublisher.unpublish user_id, project_id, (error) ->
return next(error) if error?
res.send 204
updateProjectDescription: (req, res, next) ->
project_id = req.params.Project_id
{description} = req.body
EditorController.updateProjectDescription project_id, description, (error) ->
return next(error) if error?
res.send 204
getTemplateDetails: (req, res, next)->
project_id = req.params.Project_id
ProjectGetter.getProject project_id, {owner_ref: 1}, (error, project) ->
return next(error) if error?
user_id = project.owner_ref.toString()
async.parallel {
details: (cb)->
TemplatesPublisher.getTemplateDetails user_id, project_id, cb
description: (cb)->
ProjectDetailsHandler.getProjectDescription project_id, cb
}, (err, results)->
if err?
logger.err err:err, user_id:user_id, project_id:project_id, "something went wrong getting template details"
return next(err)
details = results.details
details.description = results.description
res.json details
setCompiler = (project_id, compiler, callback)->
if compiler?
ProjectOptionsHandler.setCompiler project_id, compiler, callback
else
callback()

View file

@ -1,25 +0,0 @@
settings = require("settings-sharelatex")
logger = require("logger-sharelatex")
module.exports =
saveTemplateDataInSession: (req, res, next)->
if req.query.templateName
req.session.templateData = req.query
next()
id_or_tag_parse: (req, res, next)->
tag_or_template_id = req.params.tag_or_template_id
if _isObjectId(tag_or_template_id)
req.params.template_id = tag_or_template_id
else
req.params.tag_name = tag_or_template_id
next()
_isObjectId: _isObjectId = (tag_or_id)->
checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$")
checkForHexRegExp.test(tag_or_id)
insert_templates_user_id: (req, res, next)->
req.params.user_id = settings.templates.user_id
next()

View file

@ -1,36 +0,0 @@
request = require("request")
settings = require("settings-sharelatex")
logger = require("logger-sharelatex")
module.exports =
publish : (user_id, project_id, callback)->
url = buildUrl(user_id, project_id)
request.post url, (err)->
if err?
logger.err err:err, "something went wrong publishing project as template"
callback err
unpublish: (user_id, project_id, callback)->
url = buildUrl(user_id, project_id)
request.del url, (err)->
callback()
getTemplateDetails: (user_id, project_id, callback)->
url = buildUrl(user_id, project_id)+"/details"
request.get url, (err, res, body)->
if err?
logger.err err:err, user_id:user_id, project_id:project_id, body:body, "error getting template details"
return callback err
try
json = JSON.parse body
catch err
logger.err err:err, user_id:user_id, project_id:project_id, body:body, "error parsing project json details"
return callback err
logger.log json:json, user_id:user_id, project_id:project_id, "got template details"
callback(err, json)
buildUrl = (user_id, project_id)->
url = "#{settings.apis.templates.url}/templates/user/#{user_id}/project/#{project_id}"

View file

@ -1,30 +0,0 @@
SecurityManager = require("../../managers/SecurityManager")
AuthenticationController = require("../Authentication/AuthenticationController")
TemplatesWebController = require("./TemplatesWebController")
TemplatesController = require("./TemplatesController")
TemplatesMiddlewear = require('./TemplatesMiddlewear')
middleWear = require("./TemplatesMiddlewear")
module.exports =
apply: (app)->
app.get "/templates", middleWear.insert_templates_user_id, TemplatesWebController.renderTemplatesIndexPage
app.get "/templates/user/:user_id", TemplatesWebController.renderTemplatesIndexPage
app.get "/templates/:tag_or_template_id", middleWear.id_or_tag_parse, middleWear.insert_templates_user_id, TemplatesWebController.tagOrCanonicalPage
app.get "/templates/user/:user_id/:tag_or_template_id", middleWear.id_or_tag_parse, TemplatesWebController.tagOrCanonicalPage
app.get "/templates/:tag_name/:template_name", middleWear.insert_templates_user_id, TemplatesWebController.renerTemplateInTag
app.get "/templates/user/:user_id/:tag_name/:template_name", TemplatesWebController.renerTemplateInTag
app.get "/templates/:template_id/v/:version/:file_type", TemplatesWebController.proxyToTemplatesApi
app.post "/project/:Project_id/template/publish", SecurityManager.requestIsOwner, TemplatesController.publishProject
app.post "/project/:Project_id/template/unpublish", SecurityManager.requestIsOwner, TemplatesController.unpublishProject
app.post "/project/:Project_id/template/description", SecurityManager.requestCanModifyProject, TemplatesController.updateProjectDescription
# Make sure the /project/new/template route comes before the /project/:project_id/template route
# This is a get request so that it can be linked to.
app.get '/project/new/template', TemplatesMiddlewear.saveTemplateDataInSession, AuthenticationController.requireLogin(), TemplatesController.createProjectFromZipTemplate
app.get "/project/:Project_id/template", SecurityManager.requestCanAccessProject, TemplatesController.getTemplateDetails

View file

@ -1,102 +0,0 @@
request = require("request")
settings = require("settings-sharelatex")
logger = require("logger-sharelatex")
ErrorController = require("../Errors/ErrorController")
module.exports = TemplatesWebController =
renderTemplatesIndexPage: (req, res)->
logger.log "rendering index page of templates"
TemplatesWebController._getDataFromTemplatesApi "/user/#{req.params.user_id}", (err, data)->
if err? or !data?
logger.err err:err, "something went wrong in renderTemplatesIndexPage"
return res.send 500
data.title = "latex_templates"
res.render "templates/index", data
renerTemplateInTag: (req, res)->
{user_id, tag_name, template_name} = req.params
logger.log user_id:user_id, tag_name:tag_name, template_name:template_name, "rendering latex template page"
TemplatesWebController._getDataFromTemplatesApi "/user/#{user_id}/tag/#{tag_name}/template/#{template_name}", (err, data)->
if err? and err == 404
return ErrorController.notFound req, res
if err? or !data?
logger.err err:err, user_id:user_id, tag_name:tag_name, template_name:template_name, "something went wrong in renerTemplateInTag"
return res.send 500
data.title = data?.template?.name
res.render "templates/template", data
tagOrCanonicalPage: (req, res)->
if req.params.template_id?
TemplatesWebController._renderCanonicalPage(req, res)
else if req.params.tag_name?.toLowerCase() == "all"
TemplatesWebController._renderAllTemplatesPage(req, res)
else if req.params.tag_name?
TemplatesWebController._renderTagPage(req, res)
else
logger.log params:req.params, "problem rendering tagOrCanonicalPage"
res.send 500
proxyToTemplatesApi: (req, res)->
url = req.url
name = req.query.name or "Template"
if req.query.inline?
disposition = "inline"
else
disposition = "attachment"
res.header({"content-disposition": "#{disposition}; filename=\"#{name.replace("\"", "-")}.#{req.params.file_type}\""})
logger.log url:url, template_name: name, disposition: disposition, "proxying request to templates api"
getReq = request.get("#{settings.apis.templates.url}#{url}")
getReq.pipe(res)
getReq.on "error", (error) ->
logger.error err: error, "templates proxy API error"
res.send 500
_renderCanonicalPage: (req, res)->
{user_id, template_id} = req.params
logger.log user_id:user_id, template_id:template_id, "rendering template page"
TemplatesWebController._getDataFromTemplatesApi "/user/#{user_id}/template/#{template_id}", (err, data)->
if err? and err == 404
return ErrorController.notFound req, res
if err?
logger.err err:err, user_id:user_id, template_id:template_id, "something went wrong in _renderCanonicalPage"
return res.send 500
data.title = data?.template?.name
data.tag = null
res.render "templates/template", data
_renderAllTemplatesPage: (req, res)->
{user_id} = req.params
logger.log user_id:user_id, "rendering all templates page"
TemplatesWebController._getDataFromTemplatesApi "/user/#{user_id}/all", (err, data)->
if err? and err == 404
return ErrorController.notFound req, res
if err?
logger.err err:err, user_id:user_id, "something went wrong in _renderCanonicalPage"
return res.send 500
data.title = "all_templates"
res.render "templates/tag", data
_renderTagPage: (req, res)->
{user_id, tag_name} = req.params
logger.log user_id:user_id, tag_name:tag_name, "rendinging tag page for templates"
TemplatesWebController._getDataFromTemplatesApi "/user/#{user_id}/tag/#{tag_name}", (err, data)->
if err? and err == 404
return ErrorController.notFound req, res
if err?
logger.err err:err, user_id:user_id, tag_name:tag_name, "something went wrong in _renderCanonicalPage"
return res.send 500
data.title = data?.tag?.name
res.render "templates/tag", data
_getDataFromTemplatesApi: (path, callback)->
opts =
url: "#{settings.apis.templates.url}#{path}"
json:true
request.get opts, (err, response, data)->
if response.statusCode == 404
return callback 404
callback err, data

View file

@ -14,7 +14,6 @@ UploadsRouter = require './Features/Uploads/UploadsRouter'
metrics = require('./infrastructure/Metrics')
ReferalController = require('./Features/Referal/ReferalController')
ReferalMiddleware = require('./Features/Referal/ReferalMiddleware')
TemplatesRouter = require('./Features/Templates/TemplatesRouter')
AuthenticationController = require('./Features/Authentication/AuthenticationController')
TagsController = require("./Features/Tags/TagsController")
CollaboratorsRouter = require('./Features/Collaborators/CollaboratorsRouter')
@ -63,7 +62,6 @@ module.exports = class Router
UploadsRouter.apply(app)
PasswordResetRouter.apply(app)
StaticPagesRouter.apply(app)
TemplatesRouter.apply(app)
Modules.applyRouter(app)

View file

@ -1,80 +0,0 @@
extends ../layout
block vars
- var meta = "Over 400 LaTeX templates for journal articles, theses, CV and resumes, posters, presentations, and much more"
block content
.content.content-alt
.container
.row.template-page-header(ng-controller="SearchController")
.col-md-2
h2
a(href="/templates") #{translate("templates")}
.col-md-8
form.project-search.form-horizontal(role="form")
.form-group.has-feedback.has-feedback-left.col-md-12
input.form-control.col-md-12(type='text', ng-model='searchQueryText', ng-keyup='search()', placeholder="Search template library....")
i.fa.fa-search.form-control-feedback-left
i.fa.fa-times.form-control-feedback(
ng-click="clearSearchText()",
style="cursor: pointer;",
ng-show="searchQueryText.length > 0"
)
.col-md-2(ng-controller="MissingTemplateController")
a.btn.btn-primary(ng-click="showMissingTemplateModal()") #{translate("missing_template_question")}
.col-md-8(ng-cloak)
ul.list-unstyled
li(ng-repeat='hit in hits')
.thumbnail.searchResult
.row
a(ng-href='{{hit.url}}')
.col-md-3
img(ng-src='{{hit.image_url}}')
.col-md-7
h1(ng-bind-html='hit.name')
p(ng-bind-html='hit.description')
.row
-each tag in tags
-if(tag.totalNumberOfTemplates > 0)
.template-section-header.col-md-12
h2
a(href=tag.tagPagePath) #{tag.name}
.row
-each template in tag.exampleTemplates
.col-md-3.template-thumbnail
a(href=template.templatePagePath ? template.templatePagePath : template.canonicalUrl).thumbnail
img(src=template.thumbnailUrl)
div.caption
h3.txt-middle #{template.name}
-if(tag.totalNumberOfTemplates > 4)
.row
.col-md-12.text-center
a(href=tag.tagPagePath) View all #{tag.totalNumberOfTemplates} #{tag.name} templates »
script(type="text/ng-template", id="missingTemplateModal")
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
) ×
h3 #{translate("missing_template_question")}
.modal-body #{translate("tell_us_about_the_template")}
.modal-footer
button.btn.btn-default(
ng-click="cancel()",
)
span #{translate("dismiss")}
a.btn.btn-primary(href='mailto:team@sharelatex.com?Subject=template') #{translate("email_us")}

View file

@ -1,31 +0,0 @@
extends ../layout
mixin template(template)
.template-thumbnail
a(href=template.templatePagePath ? template.templatePagePath : template.canonicalUrl).thumbnail
img(src=template.thumbnailUrl)
div.caption
h3 #{template.name}
block content
.content.content-alt
.container
.row
.page-header
h2
a(href="/templates") #{translate("templates")}
|
a(href=tag.tagPagePath) #{tag.name}
- for (var row = 0; row <= Math.floor(templates.length / 4); row++)
.row
- for (var column = 0; column < 4; column++)
- if (templates[row*4 + column])
.col-md-3
+template(templates[row*4 + column])
//- -each template in templates
//- a(href=template.templatePagePath || template.canonicalUrl)
//- .col-md-3.template-thumbnail
//- a(href=template.templatePagePath ? template.templatePagePath : template.canonicalUrl).thumbnail
//- img(src=template.thumbnailUrl)
//- div.caption
//- h3 #{template.name}

View file

@ -1,69 +0,0 @@
extends ../layout
block vars
- var meta = template.description
- title = title + " - LaTeX Template"
block content
.content.content-alt
.container
.row
.page-header
h2
a(href="/templates") #{translate("templates")}
|
- if(tag)
a(href=tag.tagPagePath) #{tag.name}
|
| #{template.name}
.row
.col-md-6
.entry
.row
.col-md-12.template-large-pdf-preview
a(href="#{template.pdfUrl}?inline=true&name=#{template.name}")
img(src="#{template.previewUrl}")
.col-md-6
.template-details-section
h3 #{translate("about")}
div !{template.description}
div(ng-controller="openInSlController", ng-cloak).download-buttons
a.btn.btn-primary.btn-large(href=template.open_in_sharelatex_url, ng-click='open()', ng-disabled="isDisabled", rel='nofollow') {{openInSlText}}
| &nbsp;
a.btn.btn-default(
href="#{template.zipUrl}?name=#{template.name}",
rel='nofollow',
ng-click='downloadZip()',
tooltip-placement="bottom",
tooltip="#{translate('download_zip_file')}"
)
i.fa.fa-cloud-download
.template-details-section.social_buttons
.addthis_toolbox.addthis_default_style.addthis_32x32_style
a.addthis_button_facebook
a.addthis_button_twitter
a.addthis_button_google_plusone_share
a.addthis_button_compact
script(type='text/javascript', src='//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-517c16586439faa7')
h3 #{translate("comment")}
#disqus_thread
script(type='text/javascript').
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'sharelatextemplates'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
noscript
| Please enable JavaScript to view the
a(href='http://disqus.com/?ref_noscript') comments powered by Disqus.
a.dsq-brlink(href='http://disqus.com')
| comments powered by
span.logo-disqus Disqus

View file

@ -1,209 +0,0 @@
should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, '../../../../app/js/Features/Templates/TemplatesController'
describe 'TemplatesController', ->
project_id = "213432"
beforeEach ->
@request = sinon.stub()
@request.returns {
pipe:->
on:->
}
@fs = {
unlink : sinon.stub()
createWriteStream : sinon.stub().returns(on:(_, cb)->cb())
}
@ProjectUploadManager = {createProjectFromZipArchive : sinon.stub().callsArgWith(3, null, {_id:project_id})}
@dumpFolder = "dump/path"
@ProjectOptionsHandler = {setCompiler:sinon.stub().callsArgWith(2)}
@uuid = "1234"
@TemplatesPublisher =
publish: sinon.stub()
unpublish:sinon.stub()
getTemplateDetails: sinon.stub()
@ProjectDetailsHandler =
getProjectDescription:sinon.stub()
@controller = SandboxedModule.require modulePath, requires:
'../Uploads/ProjectUploadManager':@ProjectUploadManager
'../Project/ProjectOptionsHandler':@ProjectOptionsHandler
'../Project/ProjectDetailsHandler':@ProjectDetailsHandler
'../Project/ProjectGetter':@ProjectGetter = {}
'../Editor/EditorController': @EditorController = {}
'./TemplatesPublisher':@TemplatesPublisher
"logger-sharelatex":
log:->
err:->
"settings-sharelatex":
path:
dumpFolder:@dumpFolder
siteUrl: "http://localhost:3000"
apis:
templates:
url: @templateApiUrl="http://templates.sharelatex.env"
web:
url: @webApiUrl="http://web-api.sharelatex.env"
"node-uuid":v4:=>@uuid
"request": @request
"fs":@fs
@zipUrl = "%2Ftemplates%2F52fb86a81ae1e566597a25f6%2Fv%2F4%2Fzip&templateName=Moderncv%20Banking&compiler=pdflatex"
@templateName = "project name here"
@user_id = "1234"
@req =
session:
user: _id:@user_id
templateData:
zipUrl: @zipUrl
templateName: @templateName
@redirect = {}
describe 'reciving a request to create project from templates.sharelatex.com', ->
it 'should take the zip url and write it to disk', (done)->
redirect = =>
@ProjectUploadManager.createProjectFromZipArchive.calledWith(@user_id, @templateName, "#{@dumpFolder}/#{@uuid}").should.equal true
@request.calledWith("#{@templateApiUrl}#{@zipUrl}").should.equal true
@fs.unlink.calledWith("#{@dumpFolder}/#{@uuid}").should.equal true
done()
res = redirect:redirect
@controller.createProjectFromZipTemplate @req, res
it "should go to the web api if the url does not contain templates", (done)->
@req.session.templateData.zipUrl = @zipUrl = "/project/52fd24abf080d80a22000fbd/download/zip&templateName=Example_Project&compiler=xelatex"
redirect = =>
@request.calledWith("#{@webApiUrl}#{@zipUrl}").should.equal true
done()
res = redirect:redirect
@controller.createProjectFromZipTemplate @req, res
it "should go to the web api if the url has template futher down the string", (done)->
@req.session.templateData.zipUrl = @zipUrl = "/project/52fd24abf080d80a22000fbd/download/zip&templateName=templates&compiler=xelatex"
redirect = =>
@request.calledWith("#{@webApiUrl}#{@zipUrl}").should.equal true
done()
res = redirect:redirect
@controller.createProjectFromZipTemplate @req, res
describe 'publishProject', ->
beforeEach ->
@user_id = "user-id-123"
@project_id = "project-id-123"
@res =
send: sinon.stub()
@req.params =
Project_id: @project_id
@ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, {owner_ref: @user_id})
@TemplatesPublisher.publish = sinon.stub().callsArgWith(2)
@controller.publishProject @req, @res
it "should look up the project owner", ->
@ProjectGetter.getProject
.calledWith(@project_id, { owner_ref: 1 })
.should.equal true
it "should publish the template", ->
@TemplatesPublisher.publish
.calledWith(@user_id, @project_id)
.should.equal true
it "should return a success status", ->
@res.send.calledWith(204).should.equal true
describe 'unpublishProject', ->
beforeEach ->
@user_id = "user-id-123"
@project_id = "project-id-123"
@res =
send: sinon.stub()
@req.params =
Project_id: @project_id
@ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, {owner_ref: @user_id})
@TemplatesPublisher.unpublish = sinon.stub().callsArgWith(2)
@controller.unpublishProject @req, @res
it "should look up the project owner", ->
@ProjectGetter.getProject
.calledWith(@project_id, { owner_ref: 1 })
.should.equal true
it "should publish the template", ->
@TemplatesPublisher.unpublish
.calledWith(@user_id, @project_id)
.should.equal true
it "should return a success status", ->
@res.send.calledWith(204).should.equal true
describe 'settings the compiler from the query string', ->
it 'should use the said compiler', (done)->
@req.session.templateData.compiler = "xelatex"
redirect = =>
@ProjectOptionsHandler.setCompiler.calledWith(project_id, "xelatex").should.equal true
done()
res = redirect:redirect
@controller.createProjectFromZipTemplate @req, res
it 'should not call the options handler if there is not set compiler', (done)->
redirect = =>
@ProjectOptionsHandler.setCompiler.called.should.equal false
done()
res = redirect:redirect
@controller.createProjectFromZipTemplate @req, res
describe "updateProjectDescription", ->
beforeEach ->
@EditorController.updateProjectDescription = sinon.stub().callsArg(2)
@res =
send: sinon.stub()
@req.params =
Project_id: @project_id = "project-id-123"
@req.body =
description: @description = "test description"
@controller.updateProjectDescription @req, @res
it "should update the project description", ->
@EditorController.updateProjectDescription
.calledWith(@project_id, @description)
.should.equal true
it "should return a success code", ->
@res.send.calledWith(204).should.equal true
describe 'getTemplateDetails', ->
beforeEach ->
@user_id = "user-id-123"
@project_id = "project-id-123"
@res =
json: sinon.stub()
@req.params =
Project_id: @project_id
@ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, {owner_ref: @user_id})
@TemplatesPublisher.getTemplateDetails.callsArgWith(2, null, @details = {exists: true})
@ProjectDetailsHandler.getProjectDescription.callsArgWith(1, null, @description = "test description")
@controller.getTemplateDetails @req, @res
it "should get the template details for the user_id and project_id", ->
@TemplatesPublisher.getTemplateDetails
.calledWith(@user_id, @project_id)
.should.equal true
it "should return the details and description", ->
@res.json
.calledWith({
exists: @details.exists
description: @description
})
.should.equal true

View file

@ -1,64 +0,0 @@
should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, '../../../../app/js/Features/Templates/TemplatesPublisher'
expect = require("chai").expect
describe 'Templates publish', ->
beforeEach ->
@request =
post: sinon.stub().callsArgWith(1)
del: sinon.stub().callsArgWith(1)
get: sinon.stub()
@settings =
apis:
templates:
url: "http://templates.sharelatex.env"
@TemplatesPublisher = SandboxedModule.require modulePath, requires:
"request": @request
"settings-sharelatex":@settings
"logger-sharelatex":
log:->
err:->
@project_id = "12312132"
@user_id = "132jlkjdsaoij"
describe "publish", ->
it 'should post the project to the templates api', (done)->
@TemplatesPublisher.publish @user_id, @project_id, =>
uri = "#{@settings.apis.templates.url}/templates/user/#{@user_id}/project/#{@project_id}"
@request.post.calledWith(uri).should.equal true
done()
describe "unpublish", ->
it "should make a DELETE request to templates api", (done)->
@TemplatesPublisher.unpublish @user_id, @project_id, =>
uri = "#{@settings.apis.templates.url}/templates/user/#{@user_id}/project/#{@project_id}"
@request.del.calledWith(uri).should.equal true
done()
describe "getTemplateDetails", ->
it "should make a get request to templates api", (done)->
body =
exists:true
@request.get.callsArgWith(1, null, null, JSON.stringify(body))
@TemplatesPublisher.getTemplateDetails @user_id, @project_id, (err, details)=>
uri = "#{@settings.apis.templates.url}/templates/user/#{@user_id}/project/#{@project_id}/details"
@request.get.calledWith(uri).should.equal true
assert.deepEqual details, body
done()
it "should catch an error thrown from trying to parse bad json", (done)->
@request.get.callsArgWith(1, null, null, "<not json>")
@TemplatesPublisher.getTemplateDetails @user_id, @project_id, (err, details)=>
expect(err).to.exist
done()

View file

@ -1,150 +0,0 @@
should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Templates/TemplatesWebController"
expect = require("chai").expect
describe "TemplatesWebController", ->
beforeEach ->
@settings =
apis:
templates_api:
url:"templates.sharelatex.env"
@TemplatesWebController = SandboxedModule.require modulePath, requires:
"settings-sharelatex":@settings
"logger-sharelatex":
log:->
err:->
@stubbedApiData =
template:{_id:"12312321", name:"bob"}
tag: {name:"tag name"}
@TemplatesWebController._getDataFromTemplatesApi = sinon.stub().callsArgWith(1, null, @stubbedApiData)
@user_id = "12332lk3jlkj"
@tag_name = "tag-name-here"
@template_name = "template-name-here"
@template_id = "template_id_here"
@req =
params:
user_id: @user_id
@res = {}
describe "renderTemplatesIndexPage", ->
it "should get the data from the templates api", (done)->
@res.render = (viewName, data)=>
@TemplatesWebController._getDataFromTemplatesApi.calledWith("/user/#{@user_id}").should.equal true
data.should.equal @stubbedApiData
done()
@TemplatesWebController.renderTemplatesIndexPage @req, @res
describe "renerTemplateInTag", ->
it "should get the data from the templates api", (done)->
@res.render = (viewName, data)=>
@TemplatesWebController._getDataFromTemplatesApi.calledWith("/user/#{@user_id}/tag/#{@tag_name}/template/#{@template_name}").should.equal true
data.should.equal @stubbedApiData
done()
@req.params =
user_id:@user_id
template_name:@template_name
tag_name:@tag_name
@TemplatesWebController.renerTemplateInTag @req, @res
describe "tagOrCanonicalPage", ->
beforeEach ->
@TemplatesWebController._renderCanonicalPage = sinon.stub()
@TemplatesWebController._renderAllTemplatesPage = sinon.stub()
@TemplatesWebController._renderTagPage = sinon.stub()
it "should call _renderCanonicalPage if there is a template id", ()->
@req.params =
template_id:@template_id
@TemplatesWebController.tagOrCanonicalPage @req, @res
@TemplatesWebController._renderCanonicalPage.called.should.equal true
@TemplatesWebController._renderAllTemplatesPage.called.should.equal false
@TemplatesWebController._renderTagPage.called.should.equal false
it "should call _renderAllTemplatesPage the tag name is all", ()->
@req.params =
tag_name:"all"
@TemplatesWebController.tagOrCanonicalPage @req, @res
@TemplatesWebController._renderCanonicalPage.called.should.equal false
@TemplatesWebController._renderAllTemplatesPage.called.should.equal true
@TemplatesWebController._renderTagPage.called.should.equal false
it "should call _renderTagPage the tag name is set", ()->
@req.params =
tag_name:"some-tag"
@TemplatesWebController.tagOrCanonicalPage @req, @res
@TemplatesWebController._renderCanonicalPage.called.should.equal false
@TemplatesWebController._renderAllTemplatesPage.called.should.equal false
@TemplatesWebController._renderTagPage.called.should.equal true
describe "_renderCanonicalPage", ->
it "should get the data from the templates api", (done)->
@res.render = (viewName, data)=>
@TemplatesWebController._getDataFromTemplatesApi.calledWith("/user/#{@user_id}/template/#{@template_id}").should.equal true
data.tag = null
data.should.equal @stubbedApiData
done()
@req.params =
user_id:@user_id
template_id:@template_id
@TemplatesWebController._renderCanonicalPage @req, @res
describe "_renderAllTemplatesPage", ->
it "should get the data from the templates api", (done)->
@res.render = (viewName, data)=>
@TemplatesWebController._getDataFromTemplatesApi.calledWith("/user/#{@user_id}/all").should.equal true
data.should.equal @stubbedApiData
done()
@req.params =
user_id:@user_id
@TemplatesWebController._renderAllTemplatesPage @req, @res
describe "_renderTagPage", ->
it "should get the data from the templates api", (done)->
@res.render = (viewName, data)=>
@TemplatesWebController._getDataFromTemplatesApi.calledWith("/user/#{@user_id}/tag/#{@tag_name}").should.equal true
data.should.equal @stubbedApiData
done()
@req.params =
user_id:@user_id
tag_name:@tag_name
@TemplatesWebController._renderTagPage @req, @res