Commit f20afe48 authored by Patricio Bruna's avatar Patricio Bruna

first commit: 2:37 - Tengo tuto

parents
{
"parser": "babel-eslint",
"env": {
"browser": true,
"node": true,
"es6": true
},
"ecmaFeatures": {
"modules": true
},
"rules": {
}
}
# Automatically normalize line endings for all text-based files
# http://git-scm.com/docs/gitattributes#_end_of_line_conversion
* text=auto
# For the following file types, normalize line endings to LF on
# checkin and prevent conversion to CRLF when they are checked out
# (this is required in order to prevent newline related issues like,
# for example, after the build script is run)
.* text eol=lf
*.css text eol=lf
*.html text eol=lf
*.jade text eol=lf
*.js text eol=lf
*.jsx text eol=lf
*.json text eol=lf
*.less text eol=lf
*.scss text eol=lf
*.md text eol=lf
*.sh text eol=lf
*.txt text eol=lf
*.xml text eol=lf
# Include your project-specific ignores in this file
# Read about how to use .gitignore: https://help.github.com/articles/ignoring-files
dist
node_modules
.npminstall
ncp-debug.log
npm-debug.log
### OSX template
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### SublimeText template
# cache files for sublime text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
# workspace files are user-specific
*.sublime-workspace
# project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using SublimeText
# *.sublime-project
# sftp configuration file
sftp-config.json
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
.idea
{
"esnext": true
}
# sass-lint config generated by make-sass-lint-config v0.1.1
#
# The following scss-lint Linters are not yet supported by sass-lint:
# DisableLinterReason, ElsePlacement, PropertyCount, SelectorDepth
# SpaceAroundOperator, TrailingWhitespace, UnnecessaryParentReference, Compass::*
#
# The following settings/values are unsupported by sass-lint:
# Linter Indentation, option "allow_non_nested_indentation"
# Linter Indentation, option "character"
# Linter NestingDepth, option "ignore_parent_selectors"
# Linter PropertySortOrder, option "min_properties"
# Linter PropertySortOrder, option "separate_groups"
# Linter SpaceBeforeBrace, option "allow_single_line_padding"
# Linter VendorPrefix, option "identifier_list"
files:
include: '**/*.scss'
options:
formatter: stylish
merge-default-rules: false
rules:
bem-depth:
- 1
- max-depth: 3
border-zero:
- 1
- convention: none
brace-style:
- 2
- allow-single-line: true
class-name-format:
- 1
- convention: hyphenatedbem
clean-import-paths:
- 1
- filename-extension: false
leading-underscore: false
empty-line-between-blocks:
- 2
- ignore-single-line-rulesets: true
extends-before-declarations: 1
extends-before-mixins: 1
final-newline:
- 1
- include: true
force-attribute-nesting: 1
force-element-nesting: 1
force-pseudo-nesting: 1
function-name-format:
- 1
- allow-leading-underscore: true
convention: hyphenatedlowercase
hex-length:
- 1
- style: short
hex-notation:
- 1
- style: lowercase
id-name-format:
- 1
- convention: hyphenatedbem
indentation:
- 2
- size: 4
leading-zero:
- 1
- include: false
mixin-name-format:
- 0
- allow-leading-underscore: true
convention: hyphenatedlowercase
mixins-before-declarations: 1
nesting-depth:
- 1
- max-depth: 4
no-color-keyword: 1
no-color-literals: 1
no-css-comments: 1
no-debug: 1
no-duplicate-properties: 1
no-empty-rulesets: 1
no-extends: 0
no-ids: 1
no-important: 1
no-invalid-hex: 1
no-mergeable-selectors: 1
no-misspelled-properties:
- 1
- extra-properties: ['overflow-scrolling', 'font-smoothing']
no-qualifying-elements:
- 1
- allow-element-with-attribute: false
allow-element-with-class: false
allow-element-with-id: false
no-trailing-zero: 1
no-transition-all: 0
no-url-protocols: 1
no-vendor-prefixes:
- 1
- additional-identifiers: []
excluded-identifiers: []
placeholder-in-extend: 1
placeholder-name-format:
- 1
- convention: hyphenatedlowercase
property-sort-order:
- 1
- ignore-custom-properties: false
property-units:
- 1
- global:
- ch
- em
- ex
- rem
- cm
- in
- mm
- pc
- pt
- px
- q
- vh
- vw
- vmin
- vmax
- deg
- grad
- rad
- turn
- ms
- s
- Hz
- kHz
- dpi
- dpcm
- dppx
- '%'
per-property: {}
quotes:
- 1
- style: single
shorthand-values:
- 1
- allowed-shorthands:
- 1
- 2
- 3
single-line-per-selector: 2
space-after-bang:
- 2
- include: false
space-after-colon:
- 2
- include: true
space-after-comma:
- 1
- include: true
space-before-bang:
- 2
- include: true
space-before-brace:
- 2
- include: true
space-before-colon: 1
space-between-parens:
- 2
- include: false
trailing-semicolon: 2
url-quotes: 1
variable-for-property:
- 0
- properties: []
variable-name-format:
- 1
- allow-leading-underscore: true
convention: hyphenatedlowercase
zero-unit: 1
###### DRAFT ....
## Como se usa
First, instantiate the wrapper.
```javascript
var zimbraApi = new ZimbraAdminApi({
'url': 'http://zimbra.zboxapp.dev:8000/service/admin/soap',
'user': 'admin@zboxapp.dev',
'password':'12345678'
});
```
Here you see how to get basic information using a function like `getAllDomains`:
```javascript
zimbraApi.getAllDomains(function(data, err){
if (err) return console.log(err);
data.forEach(function(v){
console.log(v.id + ' ' + v.name);
})
```
Here you see how to get basic information using a function like `getAllAccounts`:
```javascript
zimbraApi.getAllAccounts(function(data, err){
if (err) return console.log(err);
data.forEach(function(v){
console.log(v.id + ' ' + v.name);
})
```
## TODOS:
Muchas, pero ya viene.
This diff is collapsed.
This diff is collapsed.
{
"name": "ZimbraAdminApi-JS",
"version": "0.0.1",
"private": true,
"dependencies": {
"crypto-browserify": "^3.11.0",
"jquery": "2.2.3",
"js-zimbra": "github:zboxapp/js-zimbra#webpack",
"merge": "^1.2.0",
"options-api": "^1.1.0",
"sprintf-js": "^1.0.3",
"validate.js": "^0.9.0"
},
"devDependencies": {
"babel": "6.3.13",
"babel-core": "6.1.18",
"babel-eslint": "^6.0.0-beta.6",
"babel-loader": "6.1.0",
"babel-plugin-add-module-exports": "0.1.2",
"babel-plugin-transform-runtime": "^6.7.5",
"babel-polyfill": "^6.7.4",
"babel-preset-es2015": "^6.3.13",
"blanket": "^1.2.3",
"chai": "3.4.1",
"eslint": "1.7.2",
"eslint-loader": "1.1.0",
"eslint-plugin-react": "^4.3.0",
"grunt": "^1.0.1",
"grunt-blanket-mocha": "^0.5.0",
"http": "0.0.0",
"http-proxy": "^1.13.2",
"imports-loader": "^0.6.5",
"json-loader": "^0.5.4",
"mocha": "2.3.4",
"webpack": "1.12.9"
},
"scripts": {
"test": "grunt mocha",
"build": "webpack",
"dev": "WEBPACK_ENV=dev webpack --progress --colors --watch",
"run": "webpack --progress --watch",
"dev-server": "webpack-dev-server"
}
}
var http = require("http"),
url = require("url"),
path = require("path"),
httpProxy = require('http-proxy'),
fs = require("fs")
proxy = httpProxy.createProxyServer({})
prefix = '/service'
staticDir = './'
port = process.argv[2] || 8000;
http.createServer(function(request, response) {
console.log(request);
if (request.url.indexOf(prefix) === 0) {
proxy.web(request, response, { target: 'https://127.0.0.1:7071', secure: false });
} else {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}
}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
// Copyright (c) 2016 ZBox, Spa. All Rights Reserved.
// See LICENSE.txt for license information.
var jszimbra = require('js-zimbra');
class Error {
constructor(err) {
this.status = err.status;
this.title = err.statusText;
this.extra = this.getErrorInfo(err.responseJSON);
}
getErrorInfo(responseJSON) {
if (responseJSON && responseJSON.Body) {
return {
'code': responseJSON.Body.Fault.Detail.Error.Code,
'reason': responseJSON.Body.Fault.Reason.Text
}
} else {
return {};
}
}
}
class ZimbraAdminApi {
constructor(auth_object) {
this.url = auth_object.url;
this.user = auth_object.user;
this.password = auth_object.password;
this._client = new jszimbra.Communication({url: auth_object.url});
this.default_params = { namespace: 'zimbraAdmin', params: { } };
}
set token (token) {
this._token = token;
}
get token () {
return this._token;
}
get client () {
return this._client;
}
options() {
return this.client.options;
}
handleError(err) {
return new Error(err);
}
handleResponse(_, response) {
console.log(response);
}
login(callback) {
let auth_object = {
'username': this.user, 'secret': this.password,
'isPassword': true, 'isAdmin': true
};
let that = this;
this.client.auth(auth_object, function(err, response){
if (err) return (callback || that.handleError)(err);
return (callback || that.handleResponse)(null, response);
});
}
buildRequest() {
let request = null;
this.client.getRequest({}, (err, req) => {
if (err) return error(err);
request = req;
});
return request;
}
makeRequest(request, resource, parse_response, success, error) {
let that = this;
this.default_params.name = `${request}Request`;
let request_object = that.buildRequest();
request_object.addRequest(this.default_params, function(err){
if (err) {
return that.handleError(err);
}
let obj = new Object(self);
obj.success = success;
obj.error = error;
obj.response_name = `${request}Response`;
obj.param_object_name = resource.toLocaleLowerCase();
that.client.send(request_object, parse_response.bind(obj));
});
}
parseResponse(err, data) {
if (err) {
return this.error(err);
}
let response_object = data.get()[this.response_name][this.param_object_name];
return this.success(response_object);
}
parseAllResponse(err, data){
if (err) {
return this.error(err);
}
let response_object = data.get()[this.response_name][this.param_object_name];
return this.success(response_object);
}
getAll(resource, success, error) {
if (this.client.token) {
this.makeRequest(`GetAll${resource}s`, resource, this.parseAllResponse, success, error);
} else {
var that = this;
let callback = function(err, response){
if (err) return this.handleError(err);
that.makeRequest(`GetAll${resource}s`, resource, that.parseAllResponse, success, error);
}
this.login(callback);
}
}
getAllDomains(success, error) {
this.getAll('Domain', success, error);
}
getAllAccounts(success, error) {
this.getAll('Account', success, error);
}
}
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = ZimbraAdminApi;
} else {
global.window.ZimbraAdminApi = ZimbraAdminApi;
}
// Copyright (c) 2016 ZBox, Spa. All Rights Reserved.
// See LICENSE.txt for license information.
import $ from 'jquery';
import jszimbra from 'js-zimbra';
import Domain from '../zimbra/domain.jsx';
import Account from '../zimbra/account.jsx';
let domain;
let account;
// función que maneja el error como corresponde
function handleError(methodName, err) {
var e = null;
try {
e = JSON.parse(err);
} catch (parseError) {
e = null;
}
console.error(methodName, e); //eslint-disable-line no-console
// Aqui deberiamos revisar si falta hacer login nuevamente
return e;
}
function error(err) {
console.error(err);
}
function success(data) {
console.log("SUCCESS");
return data;
}
export function getClientConfig(success, error) {
return $.ajax({
url: 'config/config.json',
dataType: 'json',
success,
error: function onError(xhr, status, err) {
var e = handleError('getClientConfig', err);
error(e);
}
});
}
export function login(username, secret, success, error) {
const zimbra = new jszimbra.Communication({
url: global.window.manager_config.zimbraUrl
});
zimbra.auth({
username,
secret,
isPassword: true,
isAdmin: true
}, (err) => {
if (err) {
var e = handleError('login', err);
return error(e);
}
// aqui deberiamos inicializar todas las apis
domain = new Domain(zimbra);
account = new Account(zimbra);
return success();
});
}
export function getDomain(name, by, attrs, success, error) {
console.log(domain);
if (domain) {
return domain.get(name, by, attrs,
(data) => {
// aqui formateamos la data que viene en "data"
const nuevoObj = {
dominio: 'el nombre del dominio'
}
return success(nuevoObj);
},
(err) => {
var e = handleError('getDomain', err);
error(e);
});
}
// probablemente esto lo que deba hacer es forzar un login
return error({message: 'Domain not initialized'});
}
export function getAllDomains(success, error) {
if (domain) {
return domain.getAll(
(data) => {
return success(data);
},
(err) => {
var e = handleError('getDomain', err);
error(e);
});
}
// probablemente esto lo que deba hacer es forzar un login
return error({message: 'Domain not initialized'});
}
export function getAllAccounts(success, error) {
if (account) {
return account.getAll(
(data) => {
return success(data);
},
(err) => {
var e = handleError('getDomain', err);
error(e);
});
}
// probablemente esto lo que deba hacer es forzar un login
return error({message: 'Domain not initialized'});
}
// Copyright (c) 2016 ZBox, Spa. All Rights Reserved.
// See License.txt for license information.
import keyMirror from 'keymirror';
export default {
ActionTypes: keyMirror({
RECEIVED_ERROR: null
}),
PayloadSources: keyMirror({
SERVER_ACTION: null,
VIEW_ACTION: null
}),
RESERVED_TEAM_NAMES: [
'www',
'web',
'admin',
'support',
'notify',
'test',
'demo',
'mail',
'team',
'channel',
'internal',
'localhost',
'dockerhost',
'stag',
'post',
'cluster',
'api'
],
RESERVED_USERNAMES: [
'admin',
'root'
],
MONTHS: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Juio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
KeyCodes: {
UP: 38,
DOWN: 40,
LEFT: 37,
RIGHT: 39,
BACKSPACE: 8,
ENTER: 13,
ESCAPE: 27,
SPACE: 32,
TAB: 9
}
};
// Copyright (c) 2016 ZBox, Spa. All Rights Reserved.
// See LICENSE.txt for license information.
import ZimbraAdmin from './zimbra_admin.jsx';
export default class Account extends ZimbraAdmin {
constructor(connection, name, id, attrs) {
super(connection, 'Account');
this.name = name;
this.id = id;
this.attrs = attrs;
}
}
// Copyright (c) 2016 ZBox, Spa. All Rights Reserved.
// See LICENSE.txt for license information.
import ZimbraAdmin from './zimbra_admin.jsx';
export default class DistributionList extends ZimbraAdmin {
constructor(connection, name, id, attrs) {
super(connection, 'DistributionList');
this.param_object_name = 'dl';
this.name = name;
this.id = id;
this.attrs = attrs;
}
}
// Copyright (c) 2016 ZBox, Spa. All Rights Reserved.
// See LICENSE.txt for license information.
import ZimbraAdmin from './zimbra_admin.jsx';
export default class Domain extends ZimbraAdmin {
constructor(connection) {
super(connection, 'Domain');
}
}
// Copyright (c) 2016 ZBox, Spa. All Rights Reserved.
// See LICENSE.txt for license information.
export default class zimbraAdmin {
constructor(connection, object_name) {
this.zimbra = connection;
this.object_name = object_name;
this.param_object_name = object_name.toLocaleLowerCase();
this.request = this.buildRequest();
this.params = this.buildParams();
}
return_error(err){
if (err) return error(err);
}
buildParams() {
return { namespace: 'zimbraAdmin', params: { [this.param_object_name]: {} } };
}
buildRequest() {
request = null;
this.zimbra.getRequest({}, (err, req) => {
if (err) return error(err);
request = req;
});
return request;
}
makeRequest(request_name, parse_response, success, error) {
const self = this;
this.params.name = `${request_name}Request`;
this.response_name = `${request_name}Response`;
this.request.addRequest(this.params, function(err){
if (err) {
return error(err);
}
const obj = Object.create(self);
obj.success = success;
obj.error = error;
self.zimbra.send(self.request, parse_response.bind(obj));
});
}
parseResponse(err, data) {
if (err) {
return this.error(err);
}
let response_object = data.get()[this.response_name][this.param_object_name];
return this.success(response_object);
}
parseAllResponse(err, data){
if (err) {
return this.error(err);
}
let response_object = data.get()[this.response_name][this.param_object_name];
return this.success(response_object);
}
attributesHandler() {
return {
get(target, key) {
if (target[key]) return target[key];
if (target.a[key]) return target.a[key];
return null;
}
};
}
requestParams() {
return this.params.params[this.param_object_name];
}
getAll(success, error) {
this.makeRequest(`GetAll${this.object_name}s`, this.parseAllResponse, success, error);
}
get(name, by, attrs, success, error) {
var params = this.requestParams();
params.attrs = attrs;
params.by = by;
params._content = name;
this.makeRequest(`Get${this.object_name}`, this.parseResponse, success, error);
}
}
@charset "utf-8";
body {
margin:0;
}
#mocha {
font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: 60px 50px;
}
#mocha ul,
#mocha li {
margin: 0;
padding: 0;
}
#mocha ul {
list-style: none;
}
#mocha h1,
#mocha h2 {
margin: 0;
}
#mocha h1 {
margin-top: 15px;
font-size: 1em;
font-weight: 200;
}
#mocha h1 a {
text-decoration: none;
color: inherit;
}
#mocha h1 a:hover {
text-decoration: underline;
}
#mocha .suite .suite h1 {
margin-top: 0;
font-size: .8em;
}
#mocha .hidden {
display: none;
}
#mocha h2 {
font-size: 12px;
font-weight: normal;
cursor: pointer;
}
#mocha .suite {
margin-left: 15px;
}
#mocha .test {
margin-left: 15px;
overflow: hidden;
}
#mocha .test.pending:hover h2::after {
content: '(pending)';
font-family: arial, sans-serif;
}
#mocha .test.pass.medium .duration {
background: #c09853;
}
#mocha .test.pass.slow .duration {
background: #b94a48;
}
#mocha .test.pass::before {
content: '✓';
font-size: 12px;
display: block;
float: left;
margin-right: 5px;
color: #00d6b2;
}
#mocha .test.pass .duration {
font-size: 9px;
margin-left: 5px;
padding: 2px 5px;
color: #fff;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
}
#mocha .test.pass.fast .duration {
display: none;
}
#mocha .test.pending {
color: #0b97c4;
}
#mocha .test.pending::before {
content: '◦';
color: #0b97c4;
}
#mocha .test.fail {
color: #c00;
}
#mocha .test.fail pre {
color: black;
}
#mocha .test.fail::before {
content: '✖';
font-size: 12px;
display: block;
float: left;
margin-right: 5px;
color: #c00;
}
#mocha .test pre.error {
color: #c00;
max-height: 300px;
overflow: auto;
}
/**
* (1): approximate for browsers not supporting calc
* (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border)
* ^^ seriously
*/
#mocha .test pre {
display: block;
float: left;
clear: left;
font: 12px/1.5 monaco, monospace;
margin: 5px;
padding: 15px;
border: 1px solid #eee;
max-width: 85%; /*(1)*/
max-width: calc(100% - 42px); /*(2)*/
word-wrap: break-word;
border-bottom-color: #ddd;
-webkit-border-radius: 3px;
-webkit-box-shadow: 0 1px 3px #eee;
-moz-border-radius: 3px;
-moz-box-shadow: 0 1px 3px #eee;
border-radius: 3px;
}
#mocha .test h2 {
position: relative;
}
#mocha .test a.replay {
position: absolute;
top: 3px;
right: 0;
text-decoration: none;
vertical-align: middle;
display: block;
width: 15px;
height: 15px;
line-height: 15px;
text-align: center;
background: #eee;
font-size: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
-webkit-transition: opacity 200ms;
-moz-transition: opacity 200ms;
transition: opacity 200ms;
opacity: 0.3;
color: #888;
}
#mocha .test:hover a.replay {
opacity: 1;
}
#mocha-report.pass .test.fail {
display: none;
}
#mocha-report.fail .test.pass {
display: none;
}
#mocha-report.pending .test.pass,
#mocha-report.pending .test.fail {
display: none;
}
#mocha-report.pending .test.pass.pending {
display: block;
}
#mocha-error {
color: #c00;
font-size: 1.5em;
font-weight: 100;
letter-spacing: 1px;
}
#mocha-stats {
position: fixed;
top: 15px;
right: 10px;
font-size: 12px;
margin: 0;
color: #888;
z-index: 1;
}
#mocha-stats .progress {
float: right;
padding-top: 0;
}
#mocha-stats em {
color: black;
}
#mocha-stats a {
text-decoration: none;
color: inherit;
}
#mocha-stats a:hover {
border-bottom: 1px solid #eee;
}
#mocha-stats li {
display: inline-block;
margin: 0 5px;
list-style: none;
padding-top: 11px;
}
#mocha-stats canvas {
width: 40px;
height: 40px;
}
#mocha code .comment { color: #ddd; }
#mocha code .init { color: #2f6fad; }
#mocha code .string { color: #5890ad; }
#mocha code .keyword { color: #8a6343; }
#mocha code .number { color: #2f6fad; }
@media screen and (max-device-width: 480px) {
#mocha {
margin: 60px 0px;
}
#mocha #stats {
position: absolute;
}
}
This diff is collapsed.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Basic test</title>
<link rel="stylesheet" href="css/mocha.css" type="text/css" charset="utf-8" />
</head>
<body>
<!-- Required for browser reporter -->
<div id="mocha"></div>
<script src="js/mocha.js"></script>
<script src="js/chai.js"></script>
<script src="js/sinon.js"></script>
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="../node_modules/blanket/dist/qunit/blanket.js" data-cover-only="//src/"></script>
<script type="text/javascript" src="../node_modules/grunt-blanket-mocha/support/mocha-blanket.js"></script>
<script type="text/javascript">
var expect = chai.expect;
mocha.setup('bdd');
if (window.PHANTOMJS) {
blanket.options("reporter", "../node_modules/grunt-blanket-mocha/support/grunt-reporter.js");
}
if (navigator.userAgent.indexOf('PhantomJS') < 0) {
mocha.run();
}
</script>
<script src="../lib/zimbra-admin-api.js"></script>
<script src="js/spec/test.js"></script>
</body>
</html>
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/* global describe, it, SpotifyWebApi, expect, beforeEach, afterEach, sinon */
(function() {
'use strict';
var auth_data = {
'url': 'http://zimbra.zboxapp.dev:8000/service/admin/soap',
'user': 'admin@zboxapp.dev',
'password':'12345678'
};
function loadFixture(fixtureName) {
var req = new XMLHttpRequest();
req.open('GET', 'fixtures/' + fixtureName + '.json', false);
req.send(null);
if (req.status === 200) {
return JSON.parse(req.responseText);
} else {
return null;
}
}
describe('Basic tests', function() {
this.fixtures = {
domain: loadFixture('domain')
};
it('should return error object when timeout', function() {
var api = new ZimbraAdminApi({
'url': 'http://localhost',
'user': 'user',
'password':'pass'});
api.client.options.timeout = 1000;
api.login(null, function(err){
let error = api.handleError(err);
expect(error.constructor.name).to.equal('Error');
expect(error.title).to.equal('timeout');
});
});
it('return error if wrong validation', function() {
var auth_data2 = JSON.parse(JSON.stringify(auth_data));
auth_data2.password = 'abc';
var api = new ZimbraAdminApi(auth_data2);
var callback = function(err, response) {
let error = api.handleError(err);
expect(error.constructor.name).to.equal('Error');
expect(error.title).to.equal('Internal Server Error');
expect(error.extra.code).to.equal('account.AUTH_FAILED');
}
api.login(callback);
});
it('return token if ok validation', function() {
var api = new ZimbraAdminApi(auth_data);
var callback = function(err, response) {
expect(api.client.token).to.exist;
}
api.login(callback);
});
it('should get all domains', function() {
var api = new ZimbraAdminApi(auth_data);
var success = function(d){
d.forEach(function(v){
console.log(v.name);
})
};
var error = function(d){console.log(d);};
// sucess, err (Why)?
api.getAllAccounts(function(data, err){
if (err) return console.log(err);
data.forEach(function(v){
console.log(v.id + ' ' + v.name);
})
});
});
describe('Using callbacks', function() {
// it('should get a track', function() {
// var callback = sinon.spy();
// var api = new SpotifyWebApi();
// api.getTrack('3Qm86XLflmIXVm1wcwkgDK', callback);
// that.requests[0].respond(200,
// {'Content-Type':'application/json'},
// JSON.stringify(that.fixtures.track)
// );
// expect(callback.calledWith(null, that.fixtures.track)).to.be.ok;
// expect(that.requests).to.have.length(1);
// expect(that.requests[0].url).to.equal('https://api.spotify.com/v1/tracks/3Qm86XLflmIXVm1wcwkgDK');
// });
//
// it('should get multiple tracks', function() {
// var callback = sinon.spy();
// var api = new SpotifyWebApi();
// api.getTracks(['0eGsygTp906u18L0Oimnem', '1lDWb6b6ieDQ2xT7ewTC3G'], callback);
// that.requests[0].respond(200,
// {'Content-Type':'application/json'},
// JSON.stringify(that.fixtures.tracks)
// );
// expect(callback.calledWith(null, that.fixtures.tracks)).to.be.ok;
// expect(that.requests).to.have.length(1);
// expect(that.requests[0].url).to.equal('https://api.spotify.com/v1/tracks/?ids=0eGsygTp906u18L0Oimnem%2C1lDWb6b6ieDQ2xT7ewTC3G');
// });
//
// it('should get an album', function() {
// var callback = sinon.spy();
// var api = new SpotifyWebApi();
// api.getAlbum('0sNOF9WDwhWunNAHPD3Baj', callback);
// that.requests[0].respond(200,
// {'Content-Type':'application/json'},
// JSON.stringify(that.fixtures.album)
// );
// expect(callback.calledWith(null, that.fixtures.album)).to.be.ok;
// expect(that.requests).to.have.length(1);
// expect(that.requests[0].url).to.equal('https://api.spotify.com/v1/albums/0sNOF9WDwhWunNAHPD3Baj');
// });
//
// it('should get an albums\'s tracks', function() {
// var callback = sinon.spy();
// var api = new SpotifyWebApi();
// api.getAlbumTracks('0sNOF9WDwhWunNAHPD3Baj', callback);
// that.requests[0].respond(200,
// {'Content-Type':'application/json'},
// JSON.stringify(that.fixtures.album_tracks)
// );
// expect(callback.calledWith(null, that.fixtures.album_tracks)).to.be.ok;
// expect(that.requests).to.have.length(1);
// expect(that.requests[0].url).to.equal('https://api.spotify.com/v1/albums/0sNOF9WDwhWunNAHPD3Baj/tracks');
// });
});
});
})();
// webpack.config.js
var webpack = require('webpack');
var path = require('path');
var libraryName = 'zimbra-admin-api';
var outputFile = libraryName + '.js';
var DEV = false;
const NPM_TARGET = process.env.npm_lifecycle_event; //eslint-disable-line no-process-env
if (NPM_TARGET === 'run' || NPM_TARGET === 'run-fullmap') {
DEV = true;
if (NPM_TARGET === 'run-fullmap') {
FULLMAP = true;
}
}
var config = {
entry: ['babel-polyfill', './src/index.js'],
devtool: 'source-map',
output: {
path: __dirname + '/lib',
filename: outputFile,
library: 'ZimbraAdminApi',
libraryTarget: 'var',
umdNamedDefine: true
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /(node_modules)/,
query: {
plugins: ['transform-runtime'],
cacheDirectory: DEV
}
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /(\.jsx|\.js)$/,
loader: "eslint-loader",
exclude: /node_modules/
},
{
test: /(node_modules)\/.+\.(js|jsx)$/,
loader: 'imports',
query: {
$: 'jquery',
jQuery: 'jquery'
}
}
]
},
resolve: {
root: path.resolve('./src'),
extensions: ['', '.js']
}
};
module.exports = config;
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