Commit 288f3938 authored by Vince Tozzi's avatar Vince Tozzi
Browse files

Merge branch 'refactoring_interface' of...

Merge branch 'refactoring_interface' of https://github.com/RedeMocambos/baobaxia into refactoring_relations
parents 22a5750c 27a37ee5
Showing with 295 additions and 1021 deletions
+295 -1021
define([
'jquery',
'underscore',
'backbone',
'backbone_form',
'modules/bbx/base-functions',
'modules/auth/model',
'modules/repository/model',
'modules/repository/collection',
'modules/mucua/model',
'modules/mucua/collection',
'text!templates/common/header.html',
'text!templates/common/footer.html',
'text!templates/auth/LoginTemplate.html'
], function($, _, Backbone, BackboneForm, BBXBaseFunctions, LoginModel, RepositoryModel, RepositoryCollection, MucuaModel, MucuaCollection, Header, Footer, LoginTemplate){
var LoginView = Backbone.View.extend({
// define elemento associado
//el: $('#form_login_template'),
el: $('#content'),
render: function(){
var form = new Backbone.Form({
model: new LoginModel()
}).render();
this.$el.append(form.el);
this.config = BBXBaseFunctions.getConfig();
var defaultRepository = new RepositoryModel([], {url: this.config.apiUrl + '/repository/'});
var repositories = new RepositoryCollection([], {url: this.config.apiUrl + '/repository/list'});
defaultRepository.fetch({
success: function() {
repository = defaultRepository.attributes[0];
this.config = BBXBaseFunctions.getConfig();
// com info do repositorio, pode carregar as mucuas
var mucuas = new MucuaCollection([], {url: this.config.apiUrl + '/' + repository.name + '/mucuas'});
mucuas.fetch({
success: function() {
for (var i = 0; i < mucuas.models.length; i++) {
mucua = mucuas.models[i].attributes;
$('#c2_mucua').append(new Option(mucua.note, mucua.note));
}
}
});
}
});
repositories.fetch({
success: function() {
repoObj = {};
for (var i = 0; i < repositories.models.length; i++) {
repo = repositories.models[i].attributes;
$('#c2_repository').append(new Option(repo.name, repo.name));
}
}
});
$('#footer').append(Footer);
}
});
return LoginView;
});
\ No newline at end of file
/**
* Baobaxia
* 2014
*
* bbx/base-functions.js
*
* All functions of general use, intended to be accessed by modules of the interface; includes also some private functions. The list of public functions is declared at the end of the file.
*
*/
define([
'jquery',
'underscore',
'backbone',
'json!config.json',
'modules/repository/model',
'jquery_cookie',
'views/common/HeaderView',
'modules/mucua/model',
'text!templates/common/menu.html',
'text!templates/common/busca.html',
'modules/common/HeaderView',
'modules/common/FooterView',
], function($, _, Backbone, DefaultConfig, RepositoryModel, MucuaModel, Menu, Busca, HeaderView, FooterView){
return {
initialize: function() {
console.log('inicializa functions bbx');
this.setConfig();
},
'modules/repository/model',
'json!config.json',
'text!templates/common/content.html',
'text!templates/common/sidebar.html',
'text!templates/common/usage-bar.html'
], function($, _, Backbone, jQueryCookie, HeaderView, MucuaModel, RepositoryModel, DefaultConfig, ContentTpl, SidebarTpl, UsageBarTpl){
var init = function() {
if (typeof $("body").data("bbx") === 'undefined') {
$("body").data("bbx",
{
configLoaded: false
});
}
setConfig: function(config) {
// configuracoes padrao: config.json
config = config || '';
if (typeof this.config === 'undefined') {
this.config = (config != '') ? config : DefaultConfig;
this.config['mucuaLocal'] = $.cookie('bbxMucuaLocal');
$("body").data("data").config = this.config;
// busca informacoes da mucua default na api
var defaultMucua = new MucuaModel([], {url: this.config.apiUrl + '/mucua/'});
defaultMucua.fetch({
success: function() {
$("body").data("data").config.defaultMucua = defaultMucua.attributes[0].description;
$("body").data("data").trigger("updatedConfig");
}
});
}
$("body").data("data").on("updatedConfig", function() {
this.config = $("body").data("data").config;
});
},
var configLoaded = $("body").data("bbx").configLoaded;
if (configLoaded === false) {
__setConfig(DefaultConfig);
}
}
/**
* checks if there's an opened session
*
* @return {Bool} if there's a session opened
*/
var isLogged = function() {
if ($.cookie('sessionBBX')) {
// TODO: add some session check
return true;
}
return false;
}
/**
* return home page
*
* @return {String} a url
*/
var getDefaultHome = function() {
// MAYBE, this should be a configurable field
var config = $("body").data("bbx").config,
url = '#' + config.defaultRepository.name + '/' + config.myMucua;
return url;
}
/**
* get avatar
*
* @return {String} a url
*/
var getAvatar = function() {
var avatarUrl = "",
defaultAvatar = 'avatar-default.png';
getConfig: function() {
if (typeof this.config === 'undefined')
this.setConfig();
return this.config;
},
// TODO: implement avatar
avatarUrl = "images/" + defaultAvatar;
return avatarUrl;
}
/**
* render common for internal pages at baobaxia
*
* @return [jQuery modify #header]
*/
var renderCommon = function(name) {
var data = {};
$('body').removeClass().addClass(name);
console.log('render common');
if ($('#sidebar').html() == "" ||
(typeof $('#sidebar').html() === "undefined")) {
$('#footer').before(_.template(SidebarTpl));
}
$('#content').html('');
var headerView = new HeaderView();
headerView.render(data);
}
/**
* render usage bar at footer
*
* @return [jquery modify #footer]
*/
var renderUsage = function(data) {
var data = data || '',
reStripUnit = /^([0-9\.]+)([\w]*)/,
total = data.total.match(reStripUnit);
used = data.used.match(reStripUnit);
// get repository / mucua
setBaseData: function(repository, mucua) {
repository = repository || '';
mucua = mucua || '';
this.setConfig();
if (repository != '' && mucua != '') {
// get both by url
$("body").data("data").repository = repository;
$("body").data("data").mucua = mucua;
$("body").data("data").trigger("changedData");
} else {
if (repository != '' & mucua == '') {
// repository by url, mucua by API
$("body").data("data").repository = repository;
var defaultMucua = new MucuaModel([], {url: this.config.apiUrl + '/mucua/'});
defaultMucua.fetch({
success: function() {
$("body").data("data").mucua = defaultMucua.attributes[0].description;
$("body").data("data").trigger("changedData");
}
});
} else if (repository == '' & mucua != '') {
// repository by API, mucua by url
$("body").data("data").mucua = mucua;
var defaultRepository = new RepositoryModel([], {url: this.config.apiUrl + '/repository/'});
defaultRepository.fetch({
success: function() {
$("body").data("data").repository = defaultRepository.attributes[0].name;
$("body").data("data").trigger("changedData");
}
});
} else {
// get both from API
var defaultRepository = new RepositoryModel([], {url: this.config.apiUrl + '/repository/'});
// TODO: usar jquery defered objects
// $.when(blabla.fetch(), abcd.fetch())
// .done(
// do_stuff();
// );
// http://stackoverflow.com/questions/19502719/backbone-multiple-collection-fetch
// http://api.jquery.com/category/deferred-object/
defaultRepository.fetch({
success: function() {
$("body").data("data").repository = defaultRepository.attributes[0].name;
this.config = $("body").data("data").config;
var defaultMucua = new MucuaModel([], {url: this.config.apiUrl + '/mucua/'});
defaultMucua.fetch({
success: function() {
$("body").data("data").mucua = defaultMucua.attributes[0].description;
$("body").data("data").trigger("changedData");
}
});
}
});
}
// split values from regexp
data.total = total[1];
data.totalUnit = total[2];
data.used = used[1];
data.usedUnit = used[2];
// calculate the percentages
data.usedPercent = Math.round(parseFloat(data.used) / parseFloat(data.total) * 100);
data.demandedPercent = Math.round(parseFloat(data.demanded) / parseFloat(data.total) * 100);
var compiledUsage = _.template(UsageBarTpl, data);
$('#footer').html(compiledUsage);
}
/**
* get actual mucua
*
* @config {Object} input Object with config data
* @return {None} don't return values
*/
var __getMyMucua = function() {
var config = $("body").data("bbx").config;
var myMucua = new MucuaModel([], {url: config.apiUrl + '/mucua/'});
myMucua.fetch({
success: function() {
config.myMucua = myMucua.attributes[0].description;
}
},
});
}
/**
* Get actual repository
*
* @config {Object} input Object with config data
* @return {None} don't return values (only by jQuery)
*/
var __getDefaultRepository = function() {
var config = $("body").data("bbx").config;
renderCommon: function(repository, mucua) {
repository = repository || '';
mucua = mucua || '';
// carrega partes comuns; carrega dados basicos para todos
this.setBaseData(repository, mucua);
// debug
// $("body").data("data").on("all", function(event) {console.log(event)});
//// event catchers para os carregamentos de dados
// atualizacao de repositorio e mucua
/*
$("body").data("data").on("changedData", function() {
$("body").data("data").changedData = true;
if ($("body").data("data").updatedConfig == true) {
$("body").data("data").trigger("renderFinish");
$("body").data("data").changedData = false;
$("body").data("data").updatedConfig = false;
}
});
// atualizacao das configuracoes
$("body").data("data").on("updatedConfig", function() {
$("body").data("data").updatedConfig = true;
if ($("body").data("data").changedData == true) {
$("body").data("data").trigger("renderFinish");
$("body").data("data").changedData = false;
$("body").data("data").updatedConfig = false;
}
});*/
// renderiza quando todos os dados forem carregados
// $("body").data("data").on("renderFinish", function() {
if ($("body").data("data").repository != '' && $("body").data("data").mucua != '') {
repository = (repository != '') ? repository : $("body").data("data").repository;
mucua = (mucua != '') ? mucua : $("body").data("data").mucua;
mucuaLocal = $.cookie('bbxMucuaLocal');
data = {'repository': repository, 'mucuaLocal': mucuaLocal, 'config': $("body").data("data").config};
if ($('#header').html() == '') {
var headerView = new HeaderView();
headerView.render(data);
}
if ($('#footer').html() == '') {
var footerView = new FooterView();
footerView.render(data);
}
if (typeof $('#busca-menu').html() === 'undefined') {
$('#content-full').prepend(_.template(Menu, data));
$('#busca-menu').append(_.template(Busca, data));
}
var defaultRepository = new RepositoryModel([], {url: config.apiUrl + '/repository/'});
defaultRepository.fetch({
success: function() {
config.defaultRepository = defaultRepository.attributes[0];
}
// });
$("body").data("data").renderCommon = true;
}
});
}
/**
* Get all available repositories
*
* @return {None} don't return values (only by jQuery)
*/
var __getRepositories = function() {
var config = $("body").data("bbx").config;
// TODO: puxar lista real de repositorios
//var listRepositories = new RepositoryModel([], {url: Config.apiUrl + '/repository/list'});
config.repositoriesList = [{name: 'mocambos'}]; // hardcoded enquanto nao esta funcional
}
/**
* Set configurations for the whole interface
*
* @config {Object} input Object with config data
* @return {None} don't return values (only by jQuery)
*/
var __setConfig = function(jsConfig) {
// configuracoes padrao: config.json
var jsConfig = jsConfig || '',
config = jsConfig;
$("body").data("bbx").config = jsConfig;
__getMyMucua();
__getDefaultRepository();
__getRepositories();
// so preenche quando todos tiverem carregado
var loadData = setInterval(function() {
if (typeof config.myMucua !== 'undefined' &&
typeof config.defaultRepository !== 'undefined' &&
typeof config.repositoriesList !== 'undefined') {
console.log('configs loaded!');
$("body").data("bbx").configLoaded = true;
clearInterval(loadData);
}
}, 50);
}
return {
init: init,
isLogged: isLogged,
getDefaultHome: getDefaultHome,
getAvatar: getAvatar,
renderCommon: renderCommon,
renderUsage: renderUsage
}
});
\ No newline at end of file
});
\ No newline at end of file
define([
'jquery',
'backbone',
'backbone_subroute',
'modules/bbx/base-functions',
'modules/media/collection',
'modules/media/BuscaView',
'text!templates/common/header.html',
'text!templates/common/footer.html',
], function($, Backbone, Backbone_Subroute, BBXBaseFunctions, MediaCollection, BuscaView, Header, Footer){
var Router = Backbone.SubRoute.extend({
routes: {
// bbx
'list': 'listBbxCommands',
'search/': 'busca',
'search/*subroute': 'busca',
},
initialize: function() {
console.log("module BBX loaded");
},
_getRepository: function() {
return this.prefix.split('/')[0];
},
_getMucua: function() {
return this.prefix.split('/')[1];
},
_getSubroute: function() {
return this.prefix.match(/\w+\/\w+\/$/i)[0];
},
// funcoes de mapeamento
listBbxCommands: function() {
console.log("lista comandos bbx");
},
busca: function(subroute) {
subroute = subroute || '';
repository = this._getRepository();
mucua = this._getMucua();
BBXBaseFunctions.renderCommon(repository, mucua);
var buscaView = new BuscaView();
buscaView.render(subroute);
},
});
return Router;
});
\ No newline at end of file
define([
'jquery',
'underscore',
'backbone',
'text!templates/common/footer.html',
], function($, _, Backbone, Footer){
var FooterView = Backbone.View.extend({
render: function(data) {
$('#footer').append(Footer);
}
});
return FooterView;
});
\ No newline at end of file
define([
'jquery',
'underscore',
'backbone',
'text!templates/common/index.html',
], function($, _, Backbone, Index){
var IndexView = Backbone.View.extend({
render: function(data){
$('#content').html(_.template(Index, data));
},
});
return IndexView;
});
\ No newline at end of file
define([
'jquery',
'underscore',
'backbone',
'text!templates/common/setMucuaLocal.html',
], function($, _, Backbone, Index){
var SetMucuaLocalView = Backbone.View.extend({
render: function(){
$('#content').html(_.template(Index));
$('#definirMucuaLocal').on('click', function() {
mucuaLocal = $('#mucuaLocal')[0].value;
console.log(mucuaLocal);
$.cookie('bbxMucuaLocal', mucuaLocal, { expires: 30 });
window.location.href = '#mocambos/' + mucuaLocal + '/bbx/search/';
});
},
});
return SetMucuaLocalView;
});
\ No newline at end of file
define([
'jquery',
'underscore',
'backbone',
'modules/bbx/base-functions',
'modules/media/model',
'modules/media/collection',
'modules/mucua/model',
'modules/repository/model',
'text!templates/common/menu.html',
'text!templates/common/busca.html',
'text!templates/media/MediaResults.html',
'text!templates/media/CaixaResultadoBusca.html'
], function($, _, Backbone, BBXBaseFunctions, MediaModel, MediaCollection, MucuaModel, RepositoryModel, Menu, Busca, MediaResults, CaixaResultadoBusca){
var BuscaView = Backbone.View.extend({
render: function(subroute){
/***
* Funções internas
*/
_get_termos = function(returnArray) {
var returnArray = returnArray || false,
search_url = '',
termos = '';
search_url = $('#form_busca').attr('action');
termos = new String(_.rest(search_url.split('search')));
termos = termos.replace('//', '/');
// return array
if (returnArray) {
termos = termos.substring(1);
termos = termos.split('/');
}
return termos;
}
_set_search_url = function(termos) {
base_search_url = _get_base_search_url();
termos = new String(termos);
search_url = base_search_url + "/" + termos.replace(',', '/');
$('#form_busca').attr('action', search_url);
}
_get_search_url = function() {
return $('#form_busca').attr('action');
}
_get_base_search_url = function() {
search_url = $('#form_busca').attr('action');
return _.first(search_url.split('search')) + "search";
}
_do_search = function(termo, exclude) {
termo = termo || '';
exclude = exclude || '';
base_search_url = _get_base_search_url();
// caso especifique um input
if (termo != '') {
if (termo.type == 'keyup') {
// adiciona termo à busca
arr_termos = _get_termos(true);
termo = termo.currentTarget.value;
if (!_.contains(arr_termos, termo)) {
str_termos = _get_termos();
url_search = base_search_url + str_termos + "/" + termo;
} else {
error = "Termo já existe";
console.log(error);
if (typeof $('mensage').html() === 'undefined') {
$('#media-results-content .breadcrumb').append("<h4 class='message'>" + error + "</h4>");
} else {
$('.message').html(error);
}
return false;
}
}
}
if (typeof url_search === 'undefined') {
url_search = _get_search_url();
}
_update_url(url_search);
}
_update_url = function() {
// tratamento da url
url_search = url_search.replace('//', '/');
url_search = url_search.replace(" ", "%20");
url_search = url_search.replace("+", "/");
document.location.href = url_search;
}
_add_term = function(obj) {
console.log("_add_term()...");
// abre caixa de busca de termo adicional (so uma vez, exibe)
$(obj).after('<input type="text" class="caixa_busca">');
}
_remove_term = function(e) {
console.log("_remove_term()...");
//console.log(e);
// remove termo
termoHtml = e.target.parentElement;
linhaHtml = termoHtml.parentElement;
termoExcluir = linhaHtml.firstChild.firstChild.innerHTML;
termos = _get_termos(true);
// remove item do array
termos = _.without(termos, termoExcluir);
_set_search_url(termos);
// TODO: [bug]: remover as caixas de input também
$(termoHtml).remove();
// conta elementos para ver se tem que remover o que falta
if (linhaHtml.childElementCount <= 2 ) {
$(linhaHtml).remove();
}
url_search = _get_search_url();
_update_url(url_search);
}
/***
* Tarefas
*/
mensagemBusca = "Buscando '" + subroute + "' no repositorio '" + repository + "' e na mucua '" + mucua + "'";
console.log(mensagemBusca);
// initial vars
config = $("body").data("data").config;
subroute = (subroute == null) ? '' : subroute;
frontend_url = '#' + repository + '/' + mucua + '/bbx/search/' + subroute;
$('#form_busca').attr('action', frontend_url);
// acessa api
url = config.apiUrl + '/' + repository + '/' + mucua + '/bbx/search/' + subroute;
var mediaCollection = new MediaCollection([], {url: url});
// busca termos da url
termos = [];
complete_link = '';
$.each(subroute.split("/"), function(key, term) {
if (term != '') {
complete_link = (complete_link != '') ? complete_link + '/' : '';
complete_link += term;
termos.push({repository: repository,
mucua: mucua,
termo: term,
complete_link: complete_link
});
}
});
/***
* Render do menu de termos
*/
// nao necessariamente adiciona, pode trocar
if (typeof $('#resultado-busca').html() === 'undefined') {
$('#menu').after(_.template(CaixaResultadoBusca, termos));
} else {
$('#resultado-busca').html(_.template(CaixaResultadoBusca, termos));
}
/***
* Fetch
*/
mediaCollection.fetch({
success: function() {
var data = {
emptyMessage: 'Nenhum registro encontrado!',
medias: mediaCollection.models,
config: BBXBaseFunctions.getConfig(),
_: _
};
var compiledTemplate = _.template(MediaResults, data);
$('#content').html(compiledTemplate);
}
});
/***
* Eventos
*/
$('#busca .button').click(function() { _do_search() });
$('.adicionar-termo').click(function() { _add_term(this) });
$('.remover-termo').click(function(e) { _remove_term(e) });
// TODO: [bug]: como fazer para pegar o evento somente da caixa atual, e nao de todas?
$('.caixa_busca').keyup(function(e) { if (e.keyCode == 13) { _do_search(e); console.log($('.caixa_busca')) } }); // enter
}
});
return BuscaView;
});
\ No newline at end of file
define([
'jquery',
'underscore',
'backbone',
'modules/bbx/base-functions',
'modules/media/model',
'modules/media/collection',
'modules/repository/model',
'text!templates/common/menu.html',
'text!templates/common/busca.html',
], function($, _, Backbone, BBXBaseFunctions, MediaModel, MediaCollection, Menu, Busca){
var MediaLast = Backbone.View.extend({
render: function(subroute){
console.log('view last content');
}
})
return MediaLast;
});
\ No newline at end of file
define([
'jquery',
'underscore',
'jquery_cookie',
'jquery_form',
'backbone',
'modules/bbx/base-functions',
'modules/media/model',
'text!templates/media/MediaEditForm.html'
], function($, _, jQueryCookie, jQueryForm, Backbone, BBXBaseFunctions, MediaModel, MediaEditFormTpl){
var MediaPublish = Backbone.View.extend({
render: function(uuid){
/***
* Funções internas
*/
getMediaBaseData = function() {
repository = $('body').data('data').repository;
mucua = $('body').data('data').mucua;
origin = mucua;
author = $('body').data('data').author;
baseurl = '#' + repository + '/' + mucua;
types = {
'': '',
'audio': 'audio',
'imagem': 'imagem',
'video': 'video',
'arquivo': 'arquivo'
};
//var media = { get: function(attr) {return this.attr}, }
var media = new MediaModel([]);
media.repository = repository;
media.origin = origin;
media.author = author;
media.date = '';
media.uuid = '';
media.name = '';
media.format = '';
media.license = '';
media.mediafile = '';
media.note = '';
media.tags = [];
media.type = '';
return media;
}
uploadFile = function() {
console.log('upload');
url = $('body').data('data').config.apiUrl + "/" + mediaBase.repository + "/" + mediaBase.origin + "/media/";
console.log(url);
var media = new MediaModel([], {url: url});
media.fetch({
success: function() {
var csrftoken = $.cookie('csrftoken');
$('#csrfmiddlewaretoken').attr('value', csrftoken);
}
});
// # $ curl -F "name=teste123" -F "tags=entrevista" -F "note=" -F "license=" -F "date=2013/06/07" -F "type=imagem" -F "mediafile=@img_0001.jpg" -X POST http://localhost:8000/redemocambos/dandara/media/ > /tmp/x.html
fields = {};
$('#form_media_publish :input').each(function() {
fields[this.name] = this.value;
});
// TODO: adicionar tags separadas (patrimonio, publico) a tags
data = {
name: fields['name'].value,
origin: fields['origin'].value,
author: fields['author'].value,
repository: fields['repository'].value,
tags: fields['tags'].value,
license: fields['license'].value,
date: fields['date'].value,
type: fields['type'].value,
note: fields['note'].value,
mediafile: fields['mediafile'].value
}
url = $('body').data('data').config.apiUrl + "/" + mediaBase.repository + "/" + mediaBase.origin + "/media/";
$('#form_media_publish').attr('action', url);
var media = new MediaModel([], {url: url});
}
updateMedia = function(media) {
url = $('body').data('data').config.interfaceUrl + mediaBase.repository + "/" + mediaBase.origin + "/media/" + media.uuid + '/edit';
document.location.href = url;
}
/***
* Tarefas
*/
this.config = BBXBaseFunctions.getConfig();
data = {
media: getMediaBaseData(),
licenses: {'': ''},
page: 'MediaPublish',
};
var compiledTpl = _.template(MediaEditFormTpl, data);
$('#content').html(compiledTpl);
$('#media-update .bloco-2').hide();
$('#media-update .bloco-1 .tags').hide();
$('body').data('data').on('all', function(event) {});
$('#mediafile').change(function() {uploadFile()});
// form upload progress meter
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('#form_media_publish').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
mediaSerialized = eval('('+ xhr.responseText +')');
updateMedia(mediaSerialized);
}
});
$('#submit').on('click', function() {
$('#form_media_publish').submit()
});
mediaBase = getMediaBaseData();
$('#repository').attr('value', mediaBase.repository);
$('#origin').attr('value', mediaBase.origin);
$('#author').attr('value', mediaBase.author);
// passo 1:
// - sobe titulo e arquivo (upload) - ok
// - instancia e retorna com uuid etc - ok
// - ativa preenchimento do resto, de acordo com o arquivo - ok
// - pega tipo de arquivo e formato
// - futuramente: diferenciar preenchimento por tipo de arquivo
// - preencher resto das informacoes
},
});
return MediaPublish;
});
\ No newline at end of file
define([
'jquery',
'underscore',
'jquery_cookie',
'jquery_form',
'backbone',
'modules/bbx/base-functions',
'modules/media/model',
'text!templates/media/MediaEditForm.html'
], function($, _, jQueryCookie, jQueryForm, Backbone, BBXBaseFunctions, MediaModel, MediaEditFormTpl){
var MediaUpdate = Backbone.View.extend({
render: function(uuid){
getFormData = function() {
data = $('body').data('data').data;
fields = {};
$('#form_media_publish :input').each(function() {
fields[this.name] = this.value;
});
mediafile = $('#mediafile-original').html();
// TODO: adicionar tags separadas (patrimonio, publico) a tags
media = {
name: fields.name,
origin: fields.origin,
author: fields.author,
repository: fields.repository,
tags: fields.tags,
license: fields.license,
date: fields.date,
type: fields.type,
note: fields.note,
mediafile: mediafile,
}
data.media = media;
return data;
}
swap_license = function() {
$('#license option:selected').each(function() {
l = $(this);
if (!_.isEmpty(l.val())) {
license = 'license-' + l.val();
console.log(license);
$('#license_image').attr('class', license);
}
});
}
update_media = function() {
data = getFormData();
var media = new MediaModel([data.media], {url: data.urlApi});
options = {}
options.beforeSend = function(xhr){
xhr.setRequestHeader('X-CSRFToken', $.cookie('csrftoken'));
};
//HACK para passar o objeto corretamente
media.attributes = _.clone(media.attributes[0]);
Backbone.sync('update', media, options);
}
repository = $('body').data('data').repository;
mucua = $('body').data('data').mucua;
baseurl = '#' + repository + '/' + mucua;
urlApi = $('body').data('data').config.apiUrl + '/' + repository + '/' + mucua + '/media/' + uuid;
urlMediaView = $('body').data('data').config.interfaceUrl + repository + '/' + mucua + '/media/' + uuid;
// TODO: pegar licenças da API ou outra forma
var licenses = {
'': '',
'gplv3': 'gpl v3 - gnu general public license',
'gfdl': 'gfdl - gnu free documentation license',
'lgplv3': 'lgpl v3 - gnu lesser public license',
'agplv3': 'agpl v3 - gnu affero public license',
'copyleft': 'copyleft',
'cc': 'creative commons',
'cc_nc': 'creative commons - não comercial',
'cc_ci': 'creative commons - compartilha igual',
'cc_ci_nc': 'creative commons - compartilha igual - não comercial',
'cc_sd': 'creative commons - sem derivação',
'cc_sd_nc': 'creative commons - sem derivação - não comercial'
}
// TODO: pegar da API etc
var types = {
'': '',
'audio': 'audio',
'imagem': 'imagem',
'video': 'video',
'arquivo': 'arquivo'
}
var media = new MediaModel([], {url: urlApi});
media.fetch({
success: function() {
// TODO: passar caminho da imagem preview
media.image_preview = '';
var data = {
media: media,
baseurl: baseurl,
urlApi: urlApi,
urlMediaView: urlMediaView,
licenses: licenses,
types: types,
page: 'MediaUpdate',
}
var compiledTpl = _.template(MediaEditFormTpl, data);
$('#content').html(compiledTpl);
$('body').data('data').data = data;
var csrftoken = $.cookie('csrftoken');
$('#csrfmiddlewaretoken').attr('value', csrftoken);
// eventos
$('#license').on('change', swap_license);
$('#submit').on('click', function() { update_media(); });
$('#view-media').on('click', function() {
window.location.href = urlMediaView;
});
}
});
},
});
return MediaUpdate;
});
\ No newline at end of file
define([
'jquery',
'underscore',
'backbone',
'modules/bbx/base-functions',
'modules/media/model',
'text!templates/media/MediaView.html'
], function($, _, Backbone, BBXBaseFunctions, MediaModel, MediaViewTpl){
var MediaView = Backbone.View.extend({
render: function(uuid){
console.log("busca media " + uuid);
console.log("/" + repository + "/" + mucua + "/medias/" + uuid);
this.config = BBXBaseFunctions.getConfig();
urlApi = this.config.apiUrl + '/' + repository + '/' + mucua + '/media/' + uuid;
urlMediaView = $('body').data('data').config.interfaceUrl + repository + '/' + mucua + '/media/' + uuid;
baseurl = '#' + repository + '/' + mucua;
var media = new MediaModel([], {url: urlApi});
media.fetch({
success: function() {
var data = {
media: media,
baseurl: baseurl,
urlApi: urlApi,
urlMediaView: urlMediaView,
}
var compiledTemplate = _.template(MediaViewTpl, data);
$('#content').html(compiledTemplate);
}
});
}
});
return MediaView;
});
\ No newline at end of file
/**
* Baobaxia
* 2014
*
* media/media-functions.js
*
* Media related functions
*
*/
define([
'jquery',
'underscore',
'backbone',
'modules/media/model',
'modules/media/collection',
'modules/mucua/model',
'text!templates/media/MediaDestaquesMucua.html',
'text!templates/media/MediaNovidades.html',
'text!templates/media/MediaGrid.html'
], function($, _, Backbone, MediaModel, MediaCollection, MucuaModel, MediaDestaquesMucua, MediaNovidades, MediaGrid){
var init = function() {
}
var __getConfig = function() {
return $("body").data("bbx").config;
}
// TODO: fazer uma funcao generica de buscar media
// receber um callback para executar
var getMedia = function(url, callback) {
var media = new MediaModel([], {url: url});
media.fetch({
success: function() {
var mediaData = {
medias: media.attributes,
emptyMessage: 'Nenhum conteúdo em destaque.'
};
// callback / altera
if (typeof callback == 'function') {
// execute callback
callback(mediaData);
}
}
})
};
var getMediaByMucua = function() {
var config = this.__getConfig(),
url = config.apiUrl + '/' + config.defaultRepository.name + '/' + config.myMucua + '/bbx/search';
this.getMedia(url, function(data){
$('#content').prepend(_.template(MediaDestaquesMucua))
$('#destaques-mucua .media').html(_.template(MediaGrid, data));
});
};
var getMediaByNovidades = function() {
var config = this.__getConfig(),
url = config.apiUrl + '/' + config.defaultRepository.name + '/' + config.myMucua + '/bbx/search' ;
this.getMedia(url, function(data){
$('#content').append(_.template(MediaNovidades));
$('#novidades .media').html(_.template(MediaGrid, data));
});
};
return {
__getConfig: __getConfig,
getMedia: getMedia,
getMediaByMucua: getMediaByMucua,
getMediaByNovidades: getMediaByNovidades
}
});
\ No newline at end of file
......@@ -5,71 +5,14 @@ define([
'modules/bbx/base-functions',
'modules/media/model',
'modules/media/collection',
'modules/media/MediaView',
'modules/media/MediaLast',
'modules/media/MediaPublish',
'modules/media/MediaUpdate'
], function($, Backbone, Backbone_Subroute, BBXBaseFunctions, MediaModel, MediaCollection, MediaView, MediaLast, MediaPublish, MediaUpdate){
], function($, Backbone, Backbone_Subroute, BBXBaseFunctions, MediaModel, MediaCollection){
var Router = Backbone.SubRoute.extend({
routes: {
// media
'': 'publish',
'last/:qtd': 'last',
':uuid': 'view',
':uuid/edit': 'update'
},
initialize: function() {
console.log("module Media loaded");
},
_getRepository: function() {
return this.prefix.split('/')[0];
},
_getMucua: function() {
return this.prefix.split('/')[1];
},
publish: function() {
repository = $('body').data('data').repository;
mucua = $('body').data('data').mucua;
console.log("adicionar media");
console.log("/" + repository + "/" + mucua + "/media");
BBXBaseFunctions.renderCommon(repository, mucua);
var mediaPublish = new MediaPublish();
mediaPublish.render();
},
update: function(uuid) {
repository = $('body').data('data').repository;
mucua = $('body').data('data').mucua;
console.log("update media");
console.log("/" + repository + "/" + mucua + "/media/" + uuid + "/edit");
BBXBaseFunctions.renderCommon(repository, mucua);
var mediaUpdate = new MediaUpdate();
mediaUpdate.render(uuid);
},
last: function(qdt) {
console.log("baixa ultimas medias");
repository = $("body").data("data").repository;
mucua = $("body").data("data").mucua;
BBXBaseFunctions.renderCommon(repository, mucua);
var mediaLast = new MediaLast();
mediaLast.render(uuid);
},
view: function(uuid) {
console.log("visualiza media");
repository = this._getRepository();
mucua = this._getMucua();
BBXBaseFunctions.renderCommon(repository, mucua);
var mediaView = new MediaView();
mediaView.render(uuid);
},
});
return Router;
......
define([
'jquery',
'underscore',
'backbone',
'modules/bbx/base-functions',
'modules/mocambola/model',
'text!templates/mocambola/MocambolaVisualizacao.html'
], function($, _, Backbone, BBXBaseFunctions, MocambolaModel, MocambolaVisualizacao){
var MocambolaView = Backbone.View.extend({
render: function(username){
this.config = BBXBaseFunctions.getConfig();
urlMocambola = this.config.apiUrl + repository + '/' + mucua + '/mocambola/' + username;
var mocambola = new MocambolaModel([], {url: urlMocambola});
mocambola.fetch({
success: function() {
var data = {
mocambola: mocambola,
repository: repository,
mucua: mucua
}
var compiledTemplate = _.template(MocambolaVisualizacao, data);
$('#content').html(compiledTemplate);
}
});
}
});
return MocambolaView;
});
\ No newline at end of file
......@@ -4,7 +4,6 @@ define([
'backbone'
], function($, _, Backbone) {
var MocambolaModel = Backbone.Model.extend({
idAttribute: 'id'
});
return MocambolaModel;
......
define([
'jquery',
'backbone',
'backbone_subroute',
'modules/bbx/base-functions',
'modules/mocambola/model',
'modules/mocambola/MocambolaView',
], function($, Backbone, Backbone_Subroute, BBXBaseFunctions, MocambolaModel, MocambolaView){
var Router = Backbone.SubRoute.extend({
routes: {
// mucua
'list': 'list',
':mocambola': 'view',
},
_getRepository: function() {
return this.prefix.split('/')[0];
},
_getMucua: function() {
return this.prefix.split('/')[1];
},
list: function() {
},
view: function(mocambola) {
console.log('get dados do mocambola ' + mocambola);
repository = this._getRepository();
mucua = this._getMucua();
BBXBaseFunctions.renderCommon(repository, mucua);
var mocambolaView = new MocambolaView();
mocambolaView.render(mocambola);
}
});
return Router;
});
\ No newline at end of file
......@@ -3,9 +3,9 @@ define([
'underscore',
'backbone'
], function($, _, Backbone) {
var MediaModel = Backbone.Model.extend({
var MucuaModel = Backbone.Model.extend({
idAttribute: 'uuid'
});
return MediaModel;
return MucuaModel;
});
\ No newline at end of file
......@@ -2,23 +2,33 @@ define([
'jquery',
'backbone',
'backbone_subroute',
// 'modules/mucua/model',
], function($, Backbone, Backbone_Subroute){
'modules/bbx/base-functions',
'modules/mucua/model',
'views/mucua/HomeMucua',
], function($, Backbone, BackboneSubroute, BBXBaseFunctions, MucuaModel, HomeMucua){
var Router = Backbone.SubRoute.extend({
routes: {
// mucua
'get': 'getMucua',
'*' : 'homeMucua',
'info' : 'infoMucua',
},
getMucua: function() {
//console.log(this);
repository = this.getRepository();
mucua = this.getMucua();
console.log(repository);
console.log("get mucua " + repository + "/" + mucua);
}
initialize: function() {
console.log("module mucua loaded");
},
homeMucua: function() {
console.log("home mucua");
BBXBaseFunctions.renderCommon('mucua');
var data = {};
var homeMucua = new HomeMucua();
homeMucua.render();
},
infoMucua: function() {
console.log("info mucua");
}
});
return Router;
});
\ No newline at end of file
});
define([
'jquery',
'underscore',
'backbone',
'modules/repository/model'
], function($, _, Backbone, RepositoryModel){
var RepositoryModel = Backbone.Collection.extend({
model: RepositoryModel
});
return RepositoryModel;
});
\ No newline at end of file
......@@ -4,12 +4,7 @@ define([
'backbone'
], function($, _, Backbone) {
var RepositoryModel = Backbone.Model.extend({
idAttribute: 'name',
defaults: {
name: '',
note: '',
enableSync: true
},
idAttribute: 'uuid'
});
return RepositoryModel;
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment