CCMain.m 253 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotosCameraUpload.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCBridgeSwift.h"
  35. #define alertCreateFolder 1
  36. #define alertCreateFolderCrypto 2
  37. #define alertRename 3
  38. #define alertOfflineFolder 4
  39. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  40. {
  41. CCMetadata *_metadata;
  42. BOOL _isRoot;
  43. BOOL _isViewDidLoad;
  44. BOOL _isOfflineServerUrl;
  45. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  46. BOOL _isSelectedMode;
  47. NSMutableArray *_selectedMetadatas;
  48. NSMutableArray *_queueSelector;
  49. NSUInteger _numSelectedMetadatas;
  50. UIImageView *_ImageTitleHomeCryptoCloud;
  51. UIView *_reMenuBackgroundView;
  52. UITapGestureRecognizer *_singleFingerTap;
  53. NSString *_directoryGroupBy;
  54. NSString *_directoryOrder;
  55. NSUInteger _failedAttempts;
  56. NSDate *_lockUntilDate;
  57. NSString *_fatherPermission;
  58. UIRefreshControl *_refreshControl;
  59. UIDocumentInteractionController *_docController;
  60. CCHud *_hud;
  61. CCHud *_hudDeterminate;
  62. // Datasource
  63. CCSectionDataSourceMetadata *_sectionDataSource;
  64. NSDate *_dateReadDataSource;
  65. // Search
  66. BOOL _isSearchMode;
  67. NSString *_searchFileName;
  68. NSMutableArray *_searchResultMetadatas;
  69. NSString *_depth;
  70. NSString *_noFilesSearchTitle;
  71. NSString *_noFilesSearchDescription;
  72. // Login
  73. CCLoginWeb *_loginWeb;
  74. CCLogin *_loginVC;
  75. }
  76. @end
  77. @implementation CCMain
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== Init =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (id)initWithCoder:(NSCoder *)aDecoder
  82. {
  83. if (self = [super initWithCoder:aDecoder]) {
  84. _directoryOrder = [CCUtility getOrderSettings];
  85. _directoryGroupBy = [CCUtility getGroupBySettings];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  90. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  91. }
  92. return self;
  93. }
  94. #pragma --------------------------------------------------------------------------------------------
  95. #pragma mark ===== View =====
  96. #pragma --------------------------------------------------------------------------------------------
  97. - (void)viewDidLoad
  98. {
  99. [super viewDidLoad];
  100. // init object
  101. _metadata = [CCMetadata new];
  102. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  104. _selectedMetadatas = [NSMutableArray new];
  105. _queueSelector = [NSMutableArray new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSMutableArray new];
  110. _searchFileName = @"";
  111. _depth = @"0";
  112. _noFilesSearchTitle = @"";
  113. _noFilesSearchDescription = @"";
  114. // delegate
  115. self.tableView.delegate = self;
  116. self.tableView.tableFooterView = [UIView new];
  117. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  118. self.tableView.emptyDataSetDelegate = self;
  119. self.tableView.emptyDataSetSource = self;
  120. self.searchController.delegate = self;
  121. self.searchController.searchBar.delegate = self;
  122. [[CCNetworking sharedNetworking] settingDelegate:self];
  123. // Custom Cell
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  126. // long press recognizer TableView
  127. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  128. [self.tableView addGestureRecognizer:longPressRecognizer];
  129. // Pull-to-Refresh
  130. [self createRefreshControl];
  131. // Register for 3D Touch Previewing if available
  132. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  133. {
  134. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  135. }
  136. // Back Button
  137. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  138. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  139. // reMenu Background
  140. _reMenuBackgroundView = [[UIView alloc] init];
  141. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  142. // if this is not Main (the Main uses inizializeMain)
  143. if (_isRoot == NO && app.activeAccount.length > 0) {
  144. // Settings this folder & delegate & Loading datasource
  145. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  146. // Load Datasource
  147. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  148. // Read Folder
  149. [self readFolderWithForced:NO serverUrl:_serverUrl];
  150. }
  151. // Title
  152. [self setTitle];
  153. // Search
  154. self.definesPresentationContext = YES;
  155. self.searchController.searchResultsUpdater = self;
  156. self.searchController.dimsBackgroundDuringPresentation = NO;
  157. self.tableView.tableHeaderView = self.searchController.searchBar;
  158. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  159. [self.searchController.searchBar sizeToFit];
  160. self.searchController.searchBar.delegate = self;
  161. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  162. if ([[NCManageDatabase sharedInstance] getServerVersionAccount:app.activeAccount] >= 12) {
  163. if (_isRoot)
  164. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  165. else
  166. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  167. } else {
  168. self.searchController.searchBar.scopeButtonTitles = nil;
  169. }
  170. // Hide Search Filed on Load
  171. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  172. }
  173. // Apparirà
  174. - (void)viewWillAppear:(BOOL)animated
  175. {
  176. [super viewWillAppear:animated];
  177. // test
  178. if (app.activeAccount.length == 0)
  179. return;
  180. // Settings this folder & delegate & Loading datasource
  181. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  182. [[CCNetworking sharedNetworking] settingDelegate:self];
  183. // Color
  184. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  185. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  186. if (_isSelectedMode)
  187. [self setUINavigationBarSelected];
  188. else
  189. [self setUINavigationBarDefault];
  190. // Plus Button
  191. [app plusButtonVisibile:true];
  192. }
  193. // E' arrivato
  194. - (void)viewDidAppear:(BOOL)animated
  195. {
  196. [super viewDidAppear:animated];
  197. // Active Main
  198. app.activeMain = self;
  199. // Test viewDidLoad
  200. if (_isViewDidLoad) {
  201. _isViewDidLoad = NO;
  202. } else {
  203. if (app.activeAccount.length > 0) {
  204. // Load Datasource
  205. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  206. // Read Folder
  207. [self readFolderWithForced:NO serverUrl:_serverUrl];
  208. }
  209. }
  210. // Title
  211. [self setTitle];
  212. }
  213. - (void)viewWillDisappear:(BOOL)animated
  214. {
  215. [super viewWillDisappear:animated];
  216. [self closeAllMenu];
  217. }
  218. - (void)didReceiveMemoryWarning
  219. {
  220. [super didReceiveMemoryWarning];
  221. // Dispose of any resources that can be recreated.
  222. }
  223. - (BOOL)prefersStatusBarHidden
  224. {
  225. return NO;
  226. }
  227. // detect scroll for remove keyboard in search mode
  228. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  229. {
  230. if (_isSearchMode && scrollView == self.tableView) {
  231. [self.searchController.searchBar endEditing:YES];
  232. }
  233. }
  234. - (void)changeTheming
  235. {
  236. if (self.isViewLoaded && self.view.window)
  237. [app changeTheming:self];
  238. // Refresh control
  239. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  240. // Reload Table View
  241. [self.tableView reloadData];
  242. }
  243. #pragma --------------------------------------------------------------------------------------------
  244. #pragma mark ===== Initizlize Mail =====
  245. #pragma --------------------------------------------------------------------------------------------
  246. - (void)initializeMain:(NSNotification *)notification
  247. {
  248. _directoryGroupBy = nil;
  249. _directoryOrder = nil;
  250. _dateReadDataSource = nil;
  251. // test
  252. if (app.activeAccount.length == 0)
  253. return;
  254. if ([app.listMainVC count] == 0 || _isRoot) {
  255. // This is Root
  256. _isRoot = YES;
  257. // Crypto Mode
  258. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  259. app.isCryptoCloudMode = NO;
  260. } else {
  261. app.isCryptoCloudMode = YES;
  262. }
  263. // go Home
  264. [self.navigationController popToRootViewControllerAnimated:NO];
  265. // Remove search mode
  266. [self cancelSearchBar];
  267. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  268. _isFolderEncrypted = NO;
  269. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  270. // add list
  271. [app.listMainVC setObject:self forKey:_serverUrl];
  272. // setting Networking
  273. [[CCNetworking sharedNetworking] settingDelegate:self];
  274. [[CCNetworking sharedNetworking] settingAccount];
  275. // populate shared Link & User variable
  276. NSArray *results = [[NCManageDatabase sharedInstance] getSharesAccount:app.activeAccount];
  277. app.sharesLink = results[0];
  278. app.sharesUserAndGroup = results[1];
  279. // Setting Theming
  280. [app settingThemingColorBrand];
  281. // Load Datasource
  282. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  283. // Load Folder
  284. [self readFolderWithForced:NO serverUrl:_serverUrl];
  285. // Load photo datasorce
  286. if (app.activePhotosCameraUpload)
  287. [app.activePhotosCameraUpload reloadDatasourceForced];
  288. // remove all of detail
  289. if (app.activeDetail)
  290. [app.activeDetail removeAllView];
  291. // remove all Notification Messages
  292. [app.listOfNotifications removeAllObjects];
  293. // home main
  294. app.homeMain = self;
  295. // Initializations
  296. [app applicationInitialized];
  297. } else {
  298. // reload datasource
  299. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  300. }
  301. }
  302. #pragma --------------------------------------------------------------------------------------------
  303. #pragma mark ==== DZNEmptyDataSetSource ====
  304. #pragma --------------------------------------------------------------------------------------------
  305. /*
  306. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  307. {
  308. if(_isSearchMode)
  309. return NO;
  310. else
  311. return YES;
  312. }
  313. */
  314. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  315. {
  316. return YES;
  317. }
  318. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  319. {
  320. return [UIColor whiteColor];
  321. }
  322. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  323. {
  324. if (_isSearchMode)
  325. return [UIImage imageNamed:@"searchBig"];
  326. else
  327. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  328. }
  329. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  330. {
  331. NSString *text;
  332. if (_isSearchMode)
  333. text = _noFilesSearchTitle;
  334. else
  335. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  336. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  337. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  338. }
  339. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  340. {
  341. NSString *text;
  342. if (_isSearchMode)
  343. text = _noFilesSearchDescription;
  344. else
  345. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  346. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  347. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  348. paragraph.alignment = NSTextAlignmentCenter;
  349. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  350. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  351. }
  352. #pragma --------------------------------------------------------------------------------------------
  353. #pragma mark ===== AlertView =====
  354. #pragma --------------------------------------------------------------------------------------------
  355. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  356. {
  357. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  358. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  359. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  360. if (alertView.tag == alertRename && buttonIndex == 1) {
  361. if ([_metadata.model isEqualToString:@"note"]) {
  362. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  363. } else {
  364. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  365. }
  366. }
  367. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  368. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  369. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  370. [[CCSynchronize sharedSynchronize] addOfflineFolder:dir];
  371. [self performSelector:@selector(reloadDatasource) withObject:nil];
  372. }
  373. }
  374. // accept only number char > 0
  375. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  376. {
  377. /* Retrieve a text field at an index -
  378. raises NSRangeException when textFieldIndex is out-of-bounds.
  379. The field at index 0 will be the first text field
  380. (the single field or the login field),
  381. The field at index 1 will be the password field. */
  382. /*
  383. 1> Get the Text Field in alertview
  384. 2> Get the text of that Text Field
  385. 3> Verify that text length
  386. 4> return YES or NO Based on the length
  387. */
  388. if (alertView.tag == alertOfflineFolder) return YES;
  389. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  390. }
  391. #pragma --------------------------------------------------------------------------------------------
  392. #pragma mark ===== Graphic Window =====
  393. #pragma --------------------------------------------------------------------------------------------
  394. - (void)createRefreshControl
  395. {
  396. _refreshControl = [UIRefreshControl new];
  397. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  398. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  399. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  400. [self setRefreshControl:_refreshControl];
  401. }
  402. - (void)deleteRefreshControl
  403. {
  404. [_refreshControl endRefreshing];
  405. self.refreshControl = nil;
  406. }
  407. - (void)refreshControlTarget
  408. {
  409. [self readFolderWithForced:YES serverUrl:_serverUrl];
  410. // Actuate `Peek` feedback (weak boom)
  411. AudioServicesPlaySystemSound(1519);
  412. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  413. }
  414. - (void)setTitle
  415. {
  416. // Color text self.navigationItem.title
  417. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  418. if (_isSelectedMode) {
  419. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  420. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  421. self.navigationItem.titleView = nil;
  422. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  423. } else {
  424. // we are in home : LOGO BRAND
  425. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  426. self.navigationItem.title = nil;
  427. if ([app.reachability isReachable] == NO)
  428. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  429. else
  430. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  431. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  432. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  433. [singleTap setNumberOfTapsRequired:1];
  434. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  435. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  436. } else {
  437. self.navigationItem.title = _titleMain;
  438. }
  439. }
  440. }
  441. - (void)setUINavigationBarDefault
  442. {
  443. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  444. UIBarButtonItem *buttonMore, *buttonNotification;
  445. // =
  446. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  447. buttonMore.enabled = true;
  448. // <
  449. self.navigationController.navigationBar.hidden = NO;
  450. // Notification
  451. if ([app.listOfNotifications count] > 0) {
  452. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  453. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  454. buttonNotification.enabled = true;
  455. }
  456. if (buttonNotification)
  457. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  458. else
  459. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  460. self.navigationItem.leftBarButtonItem = nil;
  461. }
  462. - (void)setUINavigationBarSelected
  463. {
  464. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  465. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  466. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  467. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  468. self.navigationItem.leftBarButtonItem = leftButton;
  469. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  470. }
  471. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  472. {
  473. [self closeAllMenu];
  474. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  475. }];
  476. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  477. }
  478. - (void)cancelSelect
  479. {
  480. [self tableViewSelect:NO];
  481. [app.reSelectMenu close];
  482. }
  483. - (void)closeAllMenu
  484. {
  485. // close Menu
  486. [app.reSelectMenu close];
  487. [app.reMainMenu close];
  488. // Close Menu Logo
  489. [CCMenuAccount dismissMenu];
  490. }
  491. #pragma --------------------------------------------------------------------------------------------
  492. #pragma mark ===== Document Picker =====
  493. #pragma --------------------------------------------------------------------------------------------
  494. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  495. {
  496. NSLog(@"Cancelled");
  497. }
  498. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  499. {
  500. NSLog(@"Cancelled");
  501. }
  502. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  503. {
  504. documentPicker.delegate = self;
  505. [self presentViewController:documentPicker animated:YES completion:nil];
  506. }
  507. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  508. {
  509. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  510. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  511. __block NSError *error;
  512. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  513. NSString *fileName = [url lastPathComponent];
  514. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  515. NSData *data = [NSData dataWithContentsOfURL:newURL];
  516. if (data && error == nil) {
  517. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  518. // Upload File
  519. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  520. } else {
  521. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  522. }
  523. } else {
  524. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  525. }
  526. }];
  527. }
  528. }
  529. - (void)openImportDocumentPicker
  530. {
  531. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  532. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  533. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  534. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  535. documentProviderMenu.delegate = self;
  536. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  537. }
  538. #pragma --------------------------------------------------------------------------------------------
  539. #pragma mark ===== Assets Picker =====
  540. #pragma --------------------------------------------------------------------------------------------
  541. - (void)openAssetsPickerController
  542. {
  543. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  544. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  545. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  546. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  547. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  548. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  549. dispatch_async(dispatch_get_main_queue(), ^{
  550. // init picker
  551. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  552. // set delegate
  553. picker.delegate = self;
  554. // to show selection order
  555. //picker.showsSelectionIndex = YES;
  556. // to present picker as a form sheet in iPad
  557. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  558. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  559. // present picker
  560. [self presentViewController:picker animated:YES completion:nil];
  561. });
  562. }];
  563. }
  564. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  565. {
  566. [picker dismissViewControllerAnimated:YES completion:^{
  567. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  568. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  569. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  570. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  571. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  572. [self presentViewController:navigationController animated:YES completion:nil];
  573. }];
  574. }
  575. #pragma --------------------------------------------------------------------------------------------
  576. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  577. #pragma --------------------------------------------------------------------------------------------
  578. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  579. {
  580. // evitiamo il rimando della eventuale photo e/o video
  581. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  582. if (tableAccount.cameraUpload) {
  583. [[NCManageDatabase sharedInstance] setAccountsCameraUploadDateAssetTypeWithAssetMediaType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  584. [[NCManageDatabase sharedInstance] setAccountsCameraUploadDateAssetTypeWithAssetMediaType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  585. }
  586. /*
  587. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  588. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  589. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  590. }
  591. */
  592. }
  593. #pragma --------------------------------------------------------------------------------------------
  594. #pragma mark ===== UnZipFile =====
  595. #pragma --------------------------------------------------------------------------------------------
  596. - (void)unZipFile:(NSString *)fileID
  597. {
  598. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  599. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  600. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  601. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  602. dispatch_async(dispatch_get_main_queue(), ^{
  603. float progress = (float) entryNumber / (float)total;
  604. [_hudDeterminate progress:progress];
  605. });
  606. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  607. dispatch_async(dispatch_get_main_queue(), ^{
  608. [_hudDeterminate hideHud];
  609. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  610. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  611. });
  612. }];
  613. });
  614. }
  615. #pragma --------------------------------------------------------------------------------------------
  616. #pragma mark ===== Create New (OpenModel) =====
  617. #pragma --------------------------------------------------------------------------------------------
  618. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  619. {
  620. UIViewController *viewController;
  621. NSString *fileName, *uuid, *fileID, *serverUrl;
  622. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  623. [self.tableView deselectRowAtIndexPath:index animated:NO];
  624. if (isnew) {
  625. fileName = nil;
  626. uuid = [CCUtility getUUID];
  627. fileID = nil;
  628. serverUrl = _serverUrl;
  629. } else {
  630. fileName = _metadata.fileName;
  631. uuid = _metadata.uuid;
  632. fileID = _metadata.fileID;
  633. serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  634. }
  635. if ([tipo isEqualToString:@"cartadicredito"])
  636. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  637. if ([tipo isEqualToString:@"bancomat"])
  638. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  639. if ([tipo isEqualToString:@"contocorrente"])
  640. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  641. if ([tipo isEqualToString:@"accountweb"])
  642. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  643. if ([tipo isEqualToString:@"patenteguida"])
  644. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  645. if ([tipo isEqualToString:@"cartaidentita"])
  646. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  647. if ([tipo isEqualToString:@"passaporto"])
  648. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  649. if ([tipo isEqualToString:@"note"]) {
  650. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  651. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  652. [self presentViewController:navigationController animated:YES completion:nil];
  653. } else {
  654. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  655. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  656. [self presentViewController:navigationController animated:YES completion:nil];
  657. }
  658. }
  659. // New folder or new photo or video
  660. - (void)returnCreate:(NSInteger)type
  661. {
  662. switch (type) {
  663. /* PLAIN */
  664. case k_returnCreateFolderPlain: {
  665. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  666. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  667. alertView.tag = alertCreateFolder;
  668. [alertView show];
  669. }
  670. break;
  671. case k_returnCreateFotoVideoPlain: {
  672. _isPickerCriptate = false;
  673. [self openAssetsPickerController];
  674. }
  675. break;
  676. case k_returnCreateFilePlain: {
  677. _isPickerCriptate = false;
  678. [self openImportDocumentPicker];
  679. }
  680. break;
  681. /* ENCRYPTED */
  682. case k_returnCreateFolderEncrypted: {
  683. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  684. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  685. alertView.tag = alertCreateFolderCrypto;
  686. [alertView show];
  687. }
  688. break;
  689. case k_returnCreateFotoVideoEncrypted: {
  690. _isPickerCriptate = true;
  691. [self openAssetsPickerController];
  692. }
  693. break;
  694. case k_returnCreateFileEncrypted: {
  695. _isPickerCriptate = true;
  696. [self openImportDocumentPicker];
  697. }
  698. break;
  699. /* UTILITY */
  700. case k_returnNote:
  701. [self openModel:@"note" isNew:true];
  702. break;
  703. case k_returnAccountWeb:
  704. [self openModel:@"accountweb" isNew:true];
  705. break;
  706. /* BANK */
  707. case k_returnCartaDiCredito:
  708. [self openModel:@"cartadicredito" isNew:true];
  709. break;
  710. case k_returnBancomat:
  711. [self openModel:@"bancomat" isNew:true];
  712. break;
  713. case k_returnContoCorrente:
  714. [self openModel:@"contocorrente" isNew:true];
  715. break;
  716. /* DOCUMENT */
  717. case k_returnPatenteGuida:
  718. [self openModel:@"patenteguida" isNew:true];
  719. break;
  720. case k_returnCartaIdentita:
  721. [self openModel:@"cartaidentita" isNew:true];
  722. break;
  723. case k_returnPassaporto:
  724. [self openModel:@"passaporto" isNew:true];
  725. break;
  726. }
  727. }
  728. #pragma --------------------------------------------------------------------------------------------
  729. #pragma mark ===== Save selected File =====
  730. #pragma --------------------------------------------------------------------------------------------
  731. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  732. {
  733. if (error)
  734. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  735. else
  736. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  737. }
  738. - (void)saveSelectedFiles
  739. {
  740. NSLog(@"[LOG] Start download selected files ...");
  741. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  742. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  743. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  744. for (CCMetadata *metadata in metadatas) {
  745. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  746. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  747. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  748. }
  749. }
  750. [_hud hideHud];
  751. });
  752. [self tableViewSelect:NO];
  753. }
  754. #pragma --------------------------------------------------------------------------------------------
  755. #pragma mark ===== Change Password =====
  756. #pragma --------------------------------------------------------------------------------------------
  757. - (void) loginSuccess:(NSInteger)loginType
  758. {
  759. [self readFolderWithForced:YES serverUrl:_serverUrl];
  760. }
  761. - (void)changePasswordAccount
  762. {
  763. // Brand
  764. if ([NCBrandOptions sharedInstance].use_login_web) {
  765. _loginWeb = [CCLoginWeb new];
  766. _loginWeb.delegate = self;
  767. _loginWeb.loginType = loginModifyPasswordUser;
  768. dispatch_async(dispatch_get_main_queue(), ^ {
  769. [_loginWeb presentModalWithDefaultTheme:self];
  770. });
  771. } else {
  772. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  773. _loginVC.delegate = self;
  774. _loginVC.loginType = loginModifyPasswordUser;
  775. [self presentViewController:_loginVC animated:YES completion:nil];
  776. }
  777. }
  778. #pragma mark -
  779. #pragma --------------------------------------------------------------------------------------------
  780. #pragma mark ===== Peek & Pop =====
  781. #pragma --------------------------------------------------------------------------------------------
  782. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  783. {
  784. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  785. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  786. if (metadata.thumbnailExists && !metadata.cryptated) {
  787. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  788. if (cell) {
  789. previewingContext.sourceRect = cell.frame;
  790. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  791. vc.delegate = self;
  792. vc.metadata = metadata;
  793. return vc;
  794. }
  795. }
  796. return nil;
  797. }
  798. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  799. {
  800. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  801. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  802. }
  803. #pragma mark -
  804. #pragma --------------------------------------------------------------------------------------------
  805. #pragma mark ==== External Sites ====
  806. #pragma --------------------------------------------------------------------------------------------
  807. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  808. {
  809. [[NCManageDatabase sharedInstance] deleteExternalSitesForAccount:app.activeAccount];
  810. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  811. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites account:app.activeAccount];
  812. }
  813. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  814. {
  815. NSLog(@"[LOG] No External Sites found");
  816. }
  817. #pragma --------------------------------------------------------------------------------------------
  818. #pragma mark ==== Activity ====
  819. #pragma --------------------------------------------------------------------------------------------
  820. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  821. {
  822. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity account:app.activeAccount];
  823. // Reload Activity Data Source
  824. [app.activeActivity reloadDatasource];
  825. }
  826. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  827. {
  828. NSLog(@"[LOG] No Activity found");
  829. }
  830. #pragma --------------------------------------------------------------------------------------------
  831. #pragma mark ==== Notification ====
  832. #pragma --------------------------------------------------------------------------------------------
  833. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  834. {
  835. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  836. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  837. // Order by date
  838. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  839. OCNotifications *notification1 = obj1, *notification2 = obj2;
  840. return [notification2.date compare: notification1.date];
  841. }];
  842. // verify if listOfNotifications is changed
  843. NSString *old = @"", *new = @"";
  844. for (OCNotifications *notification in listOfNotifications)
  845. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  846. for (OCNotifications *notification in appDelegate.listOfNotifications)
  847. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  848. if (![new isEqualToString:old]) {
  849. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  850. // reload Notification view
  851. dispatch_async(dispatch_get_main_queue(), ^{
  852. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  853. });
  854. }
  855. // Update NavigationBar
  856. if (!_isSelectedMode) {
  857. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  858. }
  859. });
  860. }
  861. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  862. {
  863. // Update NavigationBar
  864. if (!_isSelectedMode)
  865. [self setUINavigationBarDefault];
  866. }
  867. - (void)viewNotification
  868. {
  869. if ([app.listOfNotifications count] > 0) {
  870. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  871. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  872. [self presentViewController:notificationVC animated:YES completion:nil];
  873. }
  874. }
  875. #pragma --------------------------------------------------------------------------------------------
  876. #pragma mark ==== User Profile ====
  877. #pragma --------------------------------------------------------------------------------------------
  878. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  879. {
  880. if (errorCode == 401)
  881. [self changePasswordAccount];
  882. }
  883. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  884. {
  885. [[NCManageDatabase sharedInstance] setAccountsUserProfile:metadataNet.account userProfile:userProfile];
  886. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  887. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  888. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  889. if (avatar)
  890. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  891. else
  892. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  893. dispatch_async(dispatch_get_main_queue(), ^{
  894. [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserProfile" object:nil];
  895. });
  896. });
  897. }
  898. #pragma --------------------------------------------------------------------------------------------
  899. #pragma mark ==== Capabilities ====
  900. #pragma --------------------------------------------------------------------------------------------
  901. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  902. {
  903. // Change Theming color
  904. [app settingThemingColorBrand];
  905. if (errorCode == 401)
  906. [self changePasswordAccount];
  907. }
  908. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  909. {
  910. // Update capabilities db
  911. [[NCManageDatabase sharedInstance] addCapabilities:capabilities account:app.activeAccount];
  912. // ------ THEMING -----------------------------------------------------------------------
  913. // Download Theming Background & Change Theming color
  914. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  915. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  916. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  917. if (themingBackground)
  918. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  919. else
  920. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  921. }
  922. dispatch_async(dispatch_get_main_queue(), ^{
  923. [app settingThemingColorBrand];
  924. });
  925. });
  926. // ------ SEARCH ------------------------------------------------------------------------
  927. // Search bar if change version
  928. if ([[NCManageDatabase sharedInstance] getServerVersionAccount:app.activeAccount] != capabilities.versionMajor) {
  929. [self cancelSearchBar];
  930. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  931. if (capabilities.versionMajor >= 12) {
  932. if (_isRoot)
  933. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  934. else
  935. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  936. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),self.searchController.searchBar.placeholder, nil];
  937. } else {
  938. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  939. self.searchController.searchBar.scopeButtonTitles = nil;
  940. }
  941. _depth = @"0";
  942. });
  943. }
  944. // ------ GET SERVICE SERVER ------------------------------------------------------------
  945. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  946. // Read External Sites
  947. if (capabilities.isExternalSitesServerEnabled) {
  948. metadataNet.action = actionGetExternalSitesServer;
  949. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  950. }
  951. // Read Share
  952. if (capabilities.isFilesSharingAPIEnabled) {
  953. [app.sharesID removeAllObjects];
  954. metadataNet.action = actionReadShareServer;
  955. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  956. }
  957. // Read Notification
  958. metadataNet.action = actionGetNotificationServer;
  959. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  960. // Read User Profile
  961. metadataNet.action = actionGetUserProfile;
  962. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  963. // Read Activity
  964. metadataNet.action = actionGetActivityServer;
  965. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  966. }
  967. #pragma mark -
  968. #pragma --------------------------------------------------------------------------------------------
  969. #pragma mark ==== Request Server Information ====
  970. #pragma --------------------------------------------------------------------------------------------
  971. - (void)requestServerCapabilities
  972. {
  973. // test
  974. if (app.activeAccount.length == 0)
  975. return;
  976. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  977. metadataNet.action = actionGetCapabilities;
  978. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  979. }
  980. #pragma mark -
  981. #pragma --------------------------------------------------------------------------------------------
  982. #pragma mark ==== Download Thumbnail Delegate ====
  983. #pragma --------------------------------------------------------------------------------------------
  984. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  985. {
  986. __block CCCellMain *cell;
  987. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  988. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  989. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  990. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  991. if (cell.fileImageView.image == nil) {
  992. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  993. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  994. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  995. });
  996. }
  997. }
  998. }
  999. #pragma --------------------------------------------------------------------------------------------
  1000. #pragma mark ==== Download ====
  1001. #pragma --------------------------------------------------------------------------------------------
  1002. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1003. {
  1004. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1005. // File do not exists on server, remove in local
  1006. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  1007. [CCCoreData deleteFile:metadata serverUrl:serverUrl directoryUser:app.directoryUser activeAccount:app.activeAccount];
  1008. }
  1009. if ([selector isEqualToString:selectorLoadViewImage]) {
  1010. dispatch_async(dispatch_get_main_queue(), ^{
  1011. // Updating Detail
  1012. if (app.activeDetail)
  1013. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1014. // Updating Photos
  1015. if (app.activePhotosCameraUpload)
  1016. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  1017. });
  1018. } else {
  1019. if (errorCode != kCFURLErrorCancelled)
  1020. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1021. }
  1022. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1023. }
  1024. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1025. {
  1026. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1027. if (metadata == nil) return;
  1028. // Download
  1029. if ([selector isEqualToString:selectorDownloadFile]) {
  1030. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1031. }
  1032. // Synchronized
  1033. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1034. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1035. }
  1036. // add Favorite
  1037. if ([selector isEqualToString:selectorAddFavorite]) {
  1038. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1039. }
  1040. // add Offline
  1041. if ([selector isEqualToString:selectorAddOffline]) {
  1042. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  1043. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1044. }
  1045. // encrypted file
  1046. if ([selector isEqualToString:selectorEncryptFile]) {
  1047. [self encryptedFile:metadata];
  1048. }
  1049. // decrypted file
  1050. if ([selector isEqualToString:selectorDecryptFile]) {
  1051. [self decryptedFile:metadata];
  1052. }
  1053. // open View File
  1054. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1055. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1056. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1057. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1058. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1059. selector = selectorOpenIn;
  1060. } else {
  1061. _metadata = metadata;
  1062. if ([self shouldPerformSegue])
  1063. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1064. }
  1065. }
  1066. // addLocal
  1067. if ([selector isEqualToString:selectorAddLocal]) {
  1068. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1069. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1070. [CCGraphics saveIcoWithFileID:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1071. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1072. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1073. }
  1074. // Open with...
  1075. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1076. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1077. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1078. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1079. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1080. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1081. _docController.delegate = self;
  1082. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1083. }
  1084. // Save to Photo Album
  1085. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1086. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1087. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1088. // evitiamo il rimando photo
  1089. //[CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  1090. [[NCManageDatabase sharedInstance] setAccountsCameraUploadDateAssetTypeWithAssetMediaType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  1091. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1092. if (image)
  1093. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1094. else
  1095. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1096. }
  1097. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1098. // we avoid the cross-reference video
  1099. //[CCCoreData setCameraUploadDateVideo:[NSDate date]];
  1100. [[NCManageDatabase sharedInstance] setAccountsCameraUploadDateAssetTypeWithAssetMediaType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  1101. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1102. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1103. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1104. } else {
  1105. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1106. }
  1107. }
  1108. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1109. }
  1110. // Copy File
  1111. if ([selector isEqualToString:selectorLoadCopy]) {
  1112. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1113. [self copyFileToPasteboard:metadata];
  1114. }
  1115. // download and view a template
  1116. if ([selector isEqualToString:selectorLoadModelView]) {
  1117. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1118. [self openModel:metadata.model isNew:false];
  1119. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1120. }
  1121. //download file plist
  1122. if ([selector isEqualToString:selectorLoadPlist]) {
  1123. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1124. long countSelectorLoadPlist = 0;
  1125. for (NSOperation *operation in [app.netQueue operations]) {
  1126. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1127. countSelectorLoadPlist++;
  1128. }
  1129. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount]]) {
  1130. dispatch_async(dispatch_get_main_queue(), ^{
  1131. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1132. });
  1133. }
  1134. }
  1135. //selectorLoadViewImage
  1136. if ([selector isEqualToString:selectorLoadViewImage]) {
  1137. dispatch_async(dispatch_get_main_queue(), ^{
  1138. // Detail
  1139. if (app.activeDetail)
  1140. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1141. // Photos
  1142. if (app.activePhotosCameraUpload)
  1143. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1144. });
  1145. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1146. }
  1147. // if exists postselector call self with selectorPost
  1148. if ([selectorPost length] > 0)
  1149. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1150. }
  1151. - (void)downloadSelectedFiles
  1152. {
  1153. NSLog(@"[LOG] Start download selected files ...");
  1154. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1155. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1156. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1157. for (CCMetadata *metadata in selectedMetadatas) {
  1158. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1159. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1160. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDownloadFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1161. }
  1162. }
  1163. [_hud hideHud];
  1164. });
  1165. [self tableViewSelect:NO];
  1166. }
  1167. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1168. {
  1169. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, directoryID] context:nil];
  1170. for (TableMetadata *recordMetadata in records) {
  1171. if ([CCUtility isCryptoPlistString:recordMetadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, recordMetadata.fileName]] == NO && [recordMetadata.session length] == 0) {
  1172. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1173. metadataNet.action = actionDownloadFile;
  1174. metadataNet.metadata = [CCCoreData insertEntityInMetadata:recordMetadata];
  1175. metadataNet.downloadData = NO;
  1176. metadataNet.downloadPlist = YES;
  1177. metadataNet.selector = selectorLoadPlist;
  1178. metadataNet.serverUrl = serverUrl;
  1179. metadataNet.session = k_download_session_foreground;
  1180. metadataNet.taskStatus = k_taskStatusResume;
  1181. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1182. }
  1183. }
  1184. }
  1185. #pragma --------------------------------------------------------------------------------------------
  1186. #pragma mark ===== Upload new Photos/Videos =====
  1187. #pragma --------------------------------------------------------------------------------------------
  1188. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1189. {
  1190. // Automatic upload All
  1191. if([selector isEqualToString:selectorUploadAutomaticAll])
  1192. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1193. // Read File test do not exists
  1194. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1195. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1196. // reUpload
  1197. if (metadata)
  1198. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1199. }
  1200. // Print error
  1201. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1202. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1203. }
  1204. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1205. }
  1206. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1207. {
  1208. // Automatic upload All
  1209. if([selector isEqualToString:selectorUploadAutomaticAll])
  1210. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1211. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1212. [self readFolderWithForced:YES serverUrl:serverUrl];
  1213. } else {
  1214. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1215. }
  1216. }
  1217. //
  1218. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1219. //
  1220. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1221. {
  1222. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1223. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1224. });
  1225. }
  1226. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1227. {
  1228. NSArray *assets = [arguments objectAtIndex:0];
  1229. NSString *serverUrl = [arguments objectAtIndex:1];
  1230. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1231. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1232. NSString *session = [arguments objectAtIndex:4];
  1233. //NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1234. NSString *folderPhotos = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathAndName:app.activeUrl];
  1235. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1236. // Create the folder for Photos & if request the subfolders
  1237. if (![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1238. return;
  1239. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1240. for (PHAsset *asset in assets) {
  1241. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1242. NSDate *assetDate = asset.creationDate;
  1243. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1244. // Create serverUrl if use sub folder
  1245. if (useSubFolder) {
  1246. [formatter setDateFormat:@"yyyy"];
  1247. NSString *yearString = [formatter stringFromDate:assetDate];
  1248. [formatter setDateFormat:@"MM"];
  1249. NSString *monthString = [formatter stringFromDate:assetDate];
  1250. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1251. }
  1252. // Check if is in upload
  1253. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@) AND (session != NULL) AND (session != '')", app.activeAccount, directoryID, fileName];
  1254. NSArray *isRecordInSessions = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1255. if ([isRecordInSessions count] > 0) {
  1256. // next upload
  1257. continue;
  1258. } else {
  1259. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1260. metadataNet.action = actionReadFile;
  1261. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1262. metadataNet.cryptated = cryptated;
  1263. metadataNet.fileName = fileName;
  1264. metadataNet.priority = NSOperationQueuePriorityNormal;
  1265. metadataNet.session = session;
  1266. metadataNet.selector = selectorReadFileUploadFile;
  1267. metadataNet.serverUrl = serverUrl;
  1268. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1269. }
  1270. }
  1271. }
  1272. #pragma --------------------------------------------------------------------------------------------
  1273. #pragma mark ==== Read File ====
  1274. #pragma --------------------------------------------------------------------------------------------
  1275. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1276. {
  1277. // UploadFile
  1278. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1279. // File not exists
  1280. if (errorCode == 404) {
  1281. metadataNet.action = actionUploadAsset;
  1282. metadataNet.errorCode = 0;
  1283. metadataNet.selector = selectorUploadFile;
  1284. metadataNet.selectorPost = nil;
  1285. metadataNet.taskStatus = k_taskStatusResume;
  1286. if ([metadataNet.session containsString:@"wwan"])
  1287. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1288. else
  1289. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1290. } else {
  1291. // error ho many retry befor notification and go to on next asses
  1292. if (metadataNet.errorRetry < 3) {
  1293. // Retry read file
  1294. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1295. } else {
  1296. // STOP check file, view message error
  1297. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1298. }
  1299. }
  1300. }
  1301. }
  1302. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1303. {
  1304. // UploadFile
  1305. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1306. metadataNet.action = actionUploadAsset;
  1307. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1308. metadataNet.selector = selectorUploadFile;
  1309. metadataNet.selectorPost = nil;
  1310. metadataNet.taskStatus = k_taskStatusResume;
  1311. if ([metadataNet.session containsString:@"wwan"])
  1312. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1313. else
  1314. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1315. }
  1316. }
  1317. #pragma --------------------------------------------------------------------------------------------
  1318. #pragma mark ==== Read Folder ====
  1319. #pragma --------------------------------------------------------------------------------------------
  1320. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1321. {
  1322. // verify active user
  1323. //TableAccount *record = [CCCoreData getActiveAccount];
  1324. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1325. [_hud hideHud];
  1326. [_refreshControl endRefreshing];
  1327. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1328. if (message && [record.account isEqualToString:metadataNet.account])
  1329. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1330. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1331. if (errorCode == 401)
  1332. [self changePasswordAccount];
  1333. }
  1334. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1335. {
  1336. // verify active user
  1337. //TableAccount *record = [CCCoreData getActiveAccount];
  1338. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1339. if (![record.account isEqualToString:metadataNet.account])
  1340. return;
  1341. // save father e update permission
  1342. if(!_isSearchMode)
  1343. _fatherPermission = permissions;
  1344. NSArray *recordsInSessions;
  1345. if (_isSearchMode) {
  1346. recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", metadataNet.account] context:nil];
  1347. } else {
  1348. [CCCoreData updateDirectoryEtagServerUrl:metadataNet.serverUrl etag:etag activeAccount:metadataNet.account];
  1349. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadataNet.directoryID]];
  1350. recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (session != NULL) AND (session != '')", metadataNet.account, metadataNet.directoryID] context:nil];
  1351. [CCCoreData setDateReadDirectoryID:metadataNet.directoryID activeAccount:app.activeAccount];
  1352. }
  1353. for (CCMetadata *metadata in metadatas) {
  1354. // Delete Record only in Search Mode
  1355. if (_isSearchMode)
  1356. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileID = %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadata.directoryID, metadata.fileID]];
  1357. // type of file
  1358. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1359. // if crypto do not insert
  1360. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1361. // verify if the record encrypted has plist + crypto
  1362. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1363. BOOL isCryptoComplete = NO;
  1364. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1365. for (CCMetadata *completeMetadata in metadatas) {
  1366. if (completeMetadata.cryptated == NO) continue;
  1367. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1368. isCryptoComplete = YES;
  1369. break;
  1370. }
  1371. }
  1372. if (isCryptoComplete == NO) continue;
  1373. }
  1374. // verify if the record is in download/upload progress
  1375. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1376. CCMetadata *metadataDB = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName] context:nil];
  1377. // is in Upload
  1378. if (metadataDB.session && [metadataDB.session containsString:@"upload"]) {
  1379. NSString *sessionID = metadataDB.sessionID;
  1380. // rename SessionID -> fileID
  1381. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]];
  1382. metadataDB.session = @"";
  1383. metadataDB.date = metadata.date;
  1384. metadataDB.fileID = metadata.fileID;
  1385. metadataDB.rev = metadata.fileID;
  1386. metadataDB.sessionError = @"";
  1387. metadataDB.sessionID = @"";
  1388. metadataDB.sessionTaskIdentifier = k_taskIdentifierDone;
  1389. metadataDB.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1390. [CCCoreData updateMetadata:metadataDB predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, app.activeAccount] activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1391. [CCCoreData addLocalFile:metadataDB activeAccount:app.activeAccount];
  1392. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:app.directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1393. continue;
  1394. }
  1395. // download in progress
  1396. if (metadataDB.session && [metadataDB.session containsString:@"download"])
  1397. continue;
  1398. }
  1399. // end test, insert in CoreData
  1400. [CCCoreData addMetadata:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1401. }
  1402. // read plist
  1403. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1404. // File is changed ??
  1405. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1406. if (!_isSearchMode)
  1407. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1408. });
  1409. // Search Mode
  1410. if (_isSearchMode)
  1411. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1412. // this is the same directory
  1413. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1414. // reload
  1415. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1416. // stoprefresh
  1417. [_refreshControl endRefreshing];
  1418. // Enable change user
  1419. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1420. [_hud hideHud];
  1421. }
  1422. }
  1423. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1424. {
  1425. // init control
  1426. if (!serverUrl || !app.activeAccount)
  1427. return;
  1428. // Search Mode
  1429. if (_isSearchMode) {
  1430. if (forced) {
  1431. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:serverUrl directoryID:nil];
  1432. _searchFileName = @""; // forced reload searchg
  1433. }
  1434. [self updateSearchResultsForSearchController:self.searchController];
  1435. return;
  1436. }
  1437. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1438. if ([CCCoreData isDirectoryOutOfDate:k_dayForceReadFolder directoryID:directoryID activeAccount:app.activeAccount] || forced) {
  1439. if (_refreshControl.isRefreshing == NO)
  1440. [_hud visibleIndeterminateHud];
  1441. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1442. metadataNet.action = actionReadFolder;
  1443. metadataNet.date = [NSDate date];
  1444. metadataNet.directoryID = directoryID;
  1445. metadataNet.priority = NSOperationQueuePriorityHigh;
  1446. metadataNet.selector = selectorReadFolder;
  1447. metadataNet.serverUrl = serverUrl;
  1448. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1449. }
  1450. }
  1451. #pragma mark -
  1452. #pragma --------------------------------------------------------------------------------------------
  1453. #pragma mark ===== Search =====
  1454. #pragma --------------------------------------------------------------------------------------------
  1455. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1456. {
  1457. _isSearchMode = YES;
  1458. [self deleteRefreshControl];
  1459. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1460. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1461. _searchFileName = fileName;
  1462. if ([[NCManageDatabase sharedInstance] getServerVersionAccount:app.activeAccount] >= 12 && ![_depth isEqualToString:@"0"]) {
  1463. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth delegate:self];
  1464. _noFilesSearchTitle = @"";
  1465. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1466. [self.tableView reloadEmptyDataSet];
  1467. } else {
  1468. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount];
  1469. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(directoryID == %@) AND (account == %@) AND (fileNamePrint CONTAINS[cd] %@)", directoryID, app.activeAccount, fileName];
  1470. NSArray *records = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1471. [_searchResultMetadatas removeAllObjects];
  1472. for (TableMetadata *record in records)
  1473. [_searchResultMetadatas addObject:[CCCoreData insertEntityInMetadata:record]];
  1474. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1475. metadataNet.account = app.activeAccount;
  1476. metadataNet.action = actionUploadTemplate;
  1477. metadataNet.directoryID = directoryID;
  1478. metadataNet.selector = selectorSearch;
  1479. metadataNet.serverUrl = _serverUrl;
  1480. [self readFolderSuccess:metadataNet permissions:@"" etag:@"" metadatas:_searchResultMetadatas];
  1481. }
  1482. }
  1483. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1484. [self reloadDatasource];
  1485. }
  1486. }
  1487. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1488. {
  1489. [self cancelSearchBar];
  1490. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1491. }
  1492. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1493. {
  1494. _searchFileName = @"";
  1495. if (message)
  1496. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1497. }
  1498. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1499. {
  1500. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1501. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1502. }
  1503. - (void)cancelSearchBar
  1504. {
  1505. if (self.searchController.active) {
  1506. [self.searchController setActive:NO];
  1507. [self createRefreshControl];
  1508. _isSearchMode = NO;
  1509. _searchFileName = @"";
  1510. _dateReadDataSource = nil;
  1511. _searchResultMetadatas = [NSMutableArray new];
  1512. [self reloadDatasource];
  1513. }
  1514. }
  1515. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1516. {
  1517. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1518. self.searchController.searchBar.placeholder = title;
  1519. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1520. _depth = @"0";
  1521. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1522. _depth = @"1";
  1523. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1524. _depth = @"infinity";
  1525. _searchFileName = @"";
  1526. [self updateSearchResultsForSearchController:self.searchController];
  1527. }
  1528. #pragma mark -
  1529. #pragma --------------------------------------------------------------------------------------------
  1530. #pragma mark ===== Delete File or Folder =====
  1531. #pragma --------------------------------------------------------------------------------------------
  1532. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1533. {
  1534. [self deleteFileOrFolderSuccess:metadataNet];
  1535. }
  1536. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1537. {
  1538. [_queueSelector removeObject:metadataNet.selector];
  1539. if ([_queueSelector count] == 0) {
  1540. [_hud hideHud];
  1541. if (_isSearchMode)
  1542. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1543. else
  1544. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.metadata.fileID selector:metadataNet.selector];
  1545. // next
  1546. if ([_selectedMetadatas count] > 0) {
  1547. [_selectedMetadatas removeObjectAtIndex:0];
  1548. if ([_selectedMetadatas count] > 0)
  1549. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1550. }
  1551. }
  1552. }
  1553. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1554. {
  1555. if (metadata.cryptated) {
  1556. [_queueSelector addObject:selectorDeleteCrypto];
  1557. [_queueSelector addObject:selectorDeletePlist];
  1558. } else {
  1559. [_queueSelector addObject:selectorDelete];
  1560. }
  1561. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1562. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1563. }
  1564. - (void)deleteSelectionFile
  1565. {
  1566. [_selectedMetadatas removeAllObjects];
  1567. [_queueSelector removeAllObjects];
  1568. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1569. _numSelectedMetadatas = [_selectedMetadatas count];
  1570. if ([_selectedMetadatas count] > 0)
  1571. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1572. [self tableViewSelect:NO];
  1573. }
  1574. - (void)deleteFile
  1575. {
  1576. [_selectedMetadatas removeAllObjects];
  1577. [_queueSelector removeAllObjects];
  1578. _numSelectedMetadatas = 1;
  1579. [_selectedMetadatas addObject:_metadata];
  1580. if ([_selectedMetadatas count] > 0)
  1581. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1582. [self tableViewSelect:NO];
  1583. }
  1584. #pragma --------------------------------------------------------------------------------------------
  1585. #pragma mark ===== Rename / Move =====
  1586. #pragma --------------------------------------------------------------------------------------------
  1587. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1588. {
  1589. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1590. }
  1591. - (void)renameFile:(CCMetadata *)metadata fileName:(NSString *)fileName
  1592. {
  1593. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1594. }
  1595. - (void)renameNote:(CCMetadata *)metadata fileName:(NSString *)fileName
  1596. {
  1597. CCTemplates *templates = [[CCTemplates alloc] init];
  1598. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1599. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1600. if (fileNameModel) {
  1601. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1602. metadataNet.action = actionUploadTemplate;
  1603. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1604. metadataNet.fileNamePrint = fileName;
  1605. metadataNet.rev = metadata.rev;
  1606. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1607. metadataNet.session = k_upload_session_foreground;
  1608. metadataNet.taskStatus = k_taskStatusResume;
  1609. if ([CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount])
  1610. metadataNet.selectorPost = selectorAddOffline;
  1611. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1612. }
  1613. }
  1614. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1615. {
  1616. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1617. [_hud hideHud];
  1618. if (message)
  1619. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1620. [_selectedMetadatas removeAllObjects];
  1621. [_queueSelector removeAllObjects];
  1622. }
  1623. }
  1624. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1625. {
  1626. [_queueSelector removeObject:metadataNet.selector];
  1627. if ([_queueSelector count] == 0) {
  1628. [_hud hideHud];
  1629. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1630. NSString *directoryID = metadataNet.directoryID;
  1631. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1632. NSString *serverUrlTo = [CCCoreData getServerUrlFromDirectoryID:directoryIDTo activeAccount:app.activeAccount];
  1633. // FILE -> Metadata
  1634. if (metadataNet.directory == NO) {
  1635. // move metadata
  1636. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1637. }
  1638. // DIRECTORY -> Directory - CCMetadata
  1639. if (metadataNet.directory == YES) {
  1640. // delete all dir / subdir
  1641. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName] activeAccount:app.activeAccount];
  1642. // delete all metadata and local file in dir / subdir
  1643. for (NSString *directoryIDDelete in directoryIDs)
  1644. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1645. // move metadata
  1646. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1647. // Add new directory
  1648. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1649. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1650. // Check Offline
  1651. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1652. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1653. }
  1654. // reload Datasource
  1655. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1656. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1657. else
  1658. [self reloadDatasource];
  1659. // Next file
  1660. [_selectedMetadatas removeObjectAtIndex:0];
  1661. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1662. }
  1663. }
  1664. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1665. {
  1666. if ([_selectedMetadatas count] > 0) {
  1667. CCMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1668. // Plain
  1669. if (metadata.cryptated == NO) {
  1670. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1671. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1672. if(!error) {
  1673. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1674. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1675. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1676. }];
  1677. [alert addAction:ok];
  1678. [self presentViewController:alert animated:YES completion:nil];
  1679. });
  1680. return;
  1681. }
  1682. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1683. metadataNet.action = actionMoveFileOrFolder;
  1684. metadataNet.directory = metadata.directory;
  1685. metadataNet.fileID = metadata.fileID;
  1686. metadataNet.directoryID = metadata.directoryID;
  1687. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1688. metadataNet.fileName = metadata.fileName;
  1689. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1690. metadataNet.fileNameTo = metadata.fileName;
  1691. metadataNet.rev = metadata.rev;
  1692. metadataNet.selector = selectorMove;
  1693. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1694. metadataNet.serverUrlTo = serverUrlTo;
  1695. [_queueSelector addObject:metadataNet.selector];
  1696. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1697. }
  1698. // cyptated
  1699. if (metadata.cryptated == YES) {
  1700. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1701. metadataNet.action = actionMoveFileOrFolder;
  1702. metadataNet.directory = metadata.directory;
  1703. metadataNet.fileID = metadata.fileID;
  1704. metadataNet.directoryID = metadata.directoryID;
  1705. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1706. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1707. metadataNet.rev = metadata.rev;
  1708. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1709. metadataNet.serverUrlTo = serverUrlTo;
  1710. // data
  1711. metadataNet.fileName = metadata.fileNameData;
  1712. metadataNet.fileNameTo = metadata.fileNameData;
  1713. metadataNet.selector = selectorMoveCrypto;
  1714. [_queueSelector addObject:metadataNet.selector];
  1715. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1716. // plist
  1717. metadataNet.fileName = metadata.fileName;
  1718. metadataNet.fileNameTo = metadata.fileName;
  1719. metadataNet.selector = selectorMovePlist;
  1720. [_queueSelector addObject:metadataNet.selector];
  1721. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1722. }
  1723. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1724. }
  1725. }
  1726. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1727. {
  1728. [_selectedMetadatas removeAllObjects];
  1729. [_queueSelector removeAllObjects];
  1730. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1731. _numSelectedMetadatas = [_selectedMetadatas count];
  1732. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1733. [self tableViewSelect:NO];
  1734. }
  1735. - (void)moveOpenWindow:(NSArray *)indexPaths
  1736. {
  1737. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1738. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1739. viewController.delegate = self;
  1740. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1741. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1742. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1743. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1744. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1745. viewController.networkingOperationQueue = app.netQueue;
  1746. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1747. [self presentViewController:navigationController animated:YES completion:nil];
  1748. }
  1749. #pragma --------------------------------------------------------------------------------------------
  1750. #pragma mark ===== Create folder =====
  1751. #pragma --------------------------------------------------------------------------------------------
  1752. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1753. {
  1754. [_hud hideHud];
  1755. if (message)
  1756. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1757. }
  1758. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1759. {
  1760. [_hud hideHud];
  1761. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1762. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1763. // Check Offline
  1764. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1765. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1766. // Load Folder or the Datasource
  1767. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1768. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1769. } else {
  1770. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1771. }
  1772. }
  1773. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1774. {
  1775. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1776. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1777. if (![fileNameFolder length]) return;
  1778. //if (folderCameraUpload) metadataNet.serverUrl = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1779. if (folderCameraUpload) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  1780. else metadataNet.serverUrl = _serverUrl;
  1781. metadataNet.action = actionCreateFolder;
  1782. if (folderCameraUpload)
  1783. metadataNet.options = @"folderCameraUpload";
  1784. metadataNet.fileName = fileNameFolder;
  1785. metadataNet.selector = selectorCreateFolder;
  1786. metadataNet.selectorPost = selectorReadFolderForced;
  1787. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1788. if (!folderCameraUpload)
  1789. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1790. }
  1791. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1792. {
  1793. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1794. NSString *fileNamePlist;
  1795. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1796. if (![fileNameFolder length]) return;
  1797. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1798. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1799. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1800. // Create folder
  1801. metadataNet.action = actionCreateFolder;
  1802. metadataNet.fileName = fileNamePlist;
  1803. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1804. metadataNet.selector = selectorCreateFolder;
  1805. metadataNet.serverUrl = _serverUrl;
  1806. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1807. // upload plist file
  1808. metadataNet.action = actionUploadOnlyPlist;
  1809. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1810. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1811. metadataNet.selectorPost = selectorReadFolderForced;
  1812. metadataNet.serverUrl = _serverUrl;
  1813. metadataNet.session = k_upload_session_foreground;
  1814. metadataNet.taskStatus = k_taskStatusResume;
  1815. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1816. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1817. }
  1818. - (void)createFolderCameraUpload
  1819. {
  1820. NSString *cameraFolderName = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderName];
  1821. [self createFolder:cameraFolderName folderCameraUpload:YES];
  1822. //[self createFolder:[CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount] folderCameraUpload:YES];
  1823. }
  1824. #pragma --------------------------------------------------------------------------------------------
  1825. #pragma mark ===== Encrypted / Decrypted Folder =====
  1826. #pragma --------------------------------------------------------------------------------------------
  1827. - (void)encyptedDecryptedFolder
  1828. {
  1829. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1830. if (_metadata.cryptated) {
  1831. // DECRYPTED
  1832. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1833. //-------------------------- RENAME -------------------------------------------//
  1834. metadataNet.action = actionMoveFileOrFolder;
  1835. metadataNet.fileID = _metadata.fileID;
  1836. metadataNet.fileName = _metadata.fileNameData;
  1837. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1838. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1839. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1840. metadataNet.selector = selectorRename;
  1841. metadataNet.serverUrl = serverUrl;
  1842. metadataNet.serverUrlTo = serverUrl;
  1843. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1844. //-------------------------- DELETE -------------------------------------------//
  1845. metadataNet.action = actionDeleteFileDirectory;
  1846. metadataNet.fileID = _metadata.fileID;
  1847. metadataNet.fileName = _metadata.fileName;
  1848. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1849. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1850. metadataNet.selector = selectorDeletePlist;
  1851. metadataNet.selectorPost = selectorReadFolderForced;
  1852. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1853. } else {
  1854. // ENCRYPTED
  1855. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1856. // Create File Plist
  1857. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1858. //-------------------------- RENAME -------------------------------------------//
  1859. metadataNet.action = actionMoveFileOrFolder;
  1860. metadataNet.fileID = _metadata.fileID;
  1861. metadataNet.fileName = _metadata.fileName;
  1862. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1863. metadataNet.fileNameTo = fileNameCrypto;
  1864. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1865. metadataNet.selector = selectorRename;
  1866. metadataNet.serverUrl = serverUrl;
  1867. metadataNet.serverUrlTo = serverUrl;
  1868. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1869. //-------------------------- UPLOAD -------------------------------------------//
  1870. metadataNet.action = actionUploadOnlyPlist;
  1871. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1872. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1873. metadataNet.selectorPost = selectorReadFolderForced;
  1874. metadataNet.serverUrl = serverUrl;
  1875. metadataNet.session = k_upload_session_foreground;
  1876. metadataNet.taskStatus = k_taskStatusResume;
  1877. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1878. }
  1879. }
  1880. #pragma --------------------------------------------------------------------------------------------
  1881. #pragma mark ===== Encrypted/Decrypted File =====
  1882. #pragma --------------------------------------------------------------------------------------------
  1883. - (void)encryptedSelectedFiles
  1884. {
  1885. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1886. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1887. for (CCMetadata *metadata in selectedMetadatas) {
  1888. if (metadata.cryptated == NO && metadata.directory == NO)
  1889. [metadatas addObject:metadata];
  1890. }
  1891. if ([metadatas count] > 0) {
  1892. NSLog(@"[LOG] Start encrypted selected files ...");
  1893. for (CCMetadata* metadata in metadatas) {
  1894. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1895. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1896. }
  1897. }
  1898. [self tableViewSelect:NO];
  1899. }
  1900. - (void)decryptedSelectedFiles
  1901. {
  1902. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1903. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1904. for (CCMetadata *metadata in selectedMetadatas) {
  1905. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1906. [metadatas addObject:metadata];
  1907. }
  1908. if ([metadatas count] > 0) {
  1909. NSLog(@"[LOG] Start decrypted selected files ...");
  1910. for (CCMetadata* metadata in metadatas) {
  1911. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1912. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1913. }
  1914. }
  1915. [self tableViewSelect:NO];
  1916. }
  1917. - (void)cmdEncryptedDecryptedFile
  1918. {
  1919. NSString *selector;
  1920. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1921. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1922. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1923. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1924. }
  1925. - (void)encryptedFile:(CCMetadata *)metadata
  1926. {
  1927. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1928. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1929. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1930. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1931. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1932. dispatch_async(dispatch_get_main_queue(), ^{
  1933. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1934. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1935. });
  1936. } else {
  1937. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1938. }
  1939. }
  1940. - (void)decryptedFile:(CCMetadata *)metadata
  1941. {
  1942. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1943. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1944. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1945. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1946. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1947. dispatch_async(dispatch_get_main_queue(), ^{
  1948. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1949. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1950. });
  1951. } else {
  1952. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1953. }
  1954. }
  1955. #pragma --------------------------------------------------------------------------------------------
  1956. #pragma mark ===== Progress & Task Button =====
  1957. #pragma --------------------------------------------------------------------------------------------
  1958. - (void)triggerProgressTask:(NSNotification *)notification
  1959. {
  1960. NSDictionary *dict = notification.userInfo;
  1961. NSString *fileID = [dict valueForKey:@"fileID"];
  1962. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1963. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1964. float progress = [[dict valueForKey:@"progress"] floatValue];
  1965. // Check
  1966. if (!fileID)
  1967. return;
  1968. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1969. if (![serverUrl isEqualToString:_serverUrl])
  1970. return;
  1971. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1972. if (indexPath) {
  1973. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1974. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1975. else cell.progressView.progressTintColor = [UIColor blackColor];
  1976. cell.progressView.hidden = NO;
  1977. [cell.progressView setProgress:progress];
  1978. }
  1979. if (progress == 0)
  1980. [self.navigationController cancelCCProgress];
  1981. else
  1982. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1983. }
  1984. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1985. {
  1986. UITouch * touch = [[event allTouches] anyObject];
  1987. CGPoint location = [touch locationInView:self.tableView];
  1988. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1989. if (indexPath) {
  1990. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1991. if (metadata)
  1992. [self reloadTaskButton:metadata];
  1993. }
  1994. }
  1995. - (void)reloadTaskButton:(CCMetadata *)metadata
  1996. {
  1997. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1998. __block NSURLSessionTask *findTask;
  1999. // DOWNLOAD
  2000. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2001. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2002. for (NSURLSessionUploadTask *task in downloadTasks)
  2003. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2004. findTask = task;
  2005. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  2006. [task cancel];
  2007. }
  2008. if (!findTask) {
  2009. dispatch_async(dispatch_get_main_queue(), ^{
  2010. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  2011. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2012. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2013. });
  2014. }
  2015. }];
  2016. }
  2017. // UPLOAD
  2018. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2019. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2020. for (NSURLSessionUploadTask *task in uploadTasks)
  2021. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2022. findTask = task;
  2023. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  2024. [task cancel];
  2025. }
  2026. if (!findTask) {
  2027. dispatch_async(dispatch_get_main_queue(), ^{
  2028. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  2029. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2030. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2031. });
  2032. }
  2033. }];
  2034. }
  2035. }
  2036. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2037. {
  2038. UITouch * touch = [[event allTouches] anyObject];
  2039. CGPoint location = [touch locationInView:self.tableView];
  2040. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2041. if (indexPath) {
  2042. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2043. if (metadata)
  2044. [self cancelTaskButton:metadata reloadTable:YES];
  2045. }
  2046. }
  2047. - (void)cancelTaskButton:(CCMetadata *)metadata reloadTable:(BOOL)reloadTable
  2048. {
  2049. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2050. __block NSURLSessionTask *findTask;
  2051. // DOWNLOAD
  2052. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2053. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2054. for (NSURLSessionTask *task in downloadTasks)
  2055. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2056. findTask = task;
  2057. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  2058. [task cancel];
  2059. }
  2060. if (!findTask) {
  2061. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  2062. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2063. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2064. }
  2065. }];
  2066. }
  2067. // UPLOAD
  2068. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2069. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2070. for (NSURLSessionUploadTask *task in uploadTasks)
  2071. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2072. findTask = task;
  2073. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  2074. [task cancel];
  2075. }
  2076. if (!findTask) {
  2077. dispatch_async(dispatch_get_main_queue(), ^{
  2078. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  2079. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2080. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2081. });
  2082. }
  2083. }];
  2084. }
  2085. }
  2086. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2087. {
  2088. UITouch * touch = [[event allTouches] anyObject];
  2089. CGPoint location = [touch locationInView:self.tableView];
  2090. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2091. if (indexPath) {
  2092. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2093. if (metadata)
  2094. [self stopTaskButton:metadata];
  2095. }
  2096. }
  2097. - (void)stopTaskButton:(CCMetadata *)metadata
  2098. {
  2099. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2100. __block NSURLSessionTask *findTask;
  2101. // UPLOAD
  2102. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2103. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2104. for (NSURLSessionUploadTask *task in uploadTasks)
  2105. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2106. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  2107. findTask = task;
  2108. [task cancel];
  2109. }
  2110. if (!findTask) {
  2111. dispatch_async(dispatch_get_main_queue(), ^{
  2112. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  2113. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2114. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2115. });
  2116. }
  2117. }];
  2118. }
  2119. }
  2120. #pragma --------------------------------------------------------------------------------------------
  2121. #pragma mark ===== Shared =====
  2122. #pragma --------------------------------------------------------------------------------------------
  2123. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2124. {
  2125. [_hud hideHud];
  2126. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2127. // change account ?
  2128. //TableAccount *record = [CCCoreData getActiveAccount];
  2129. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2130. if([record.account isEqualToString:metadataNet.account] == NO)
  2131. return;
  2132. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items account:appDelegate.activeAccount activeUrl:appDelegate.activeUrl];
  2133. appDelegate.sharesLink = result[0];
  2134. appDelegate.sharesUserAndGroup = result[1];
  2135. if (openWindow) {
  2136. if (_shareOC) {
  2137. [_shareOC reloadData];
  2138. } else {
  2139. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2140. // Apriamo la view
  2141. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2142. _shareOC.delegate = self;
  2143. _shareOC.metadata = metadata;
  2144. _shareOC.serverUrl = metadataNet.serverUrl;
  2145. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2146. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2147. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2148. [self presentViewController:_shareOC animated:YES completion:nil];
  2149. }
  2150. }
  2151. [self tableViewReload];
  2152. }
  2153. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2154. {
  2155. [_hud hideHud];
  2156. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2157. if (_shareOC)
  2158. [_shareOC reloadData];
  2159. [self tableViewReload];
  2160. if (errorCode == 401)
  2161. [self changePasswordAccount];
  2162. }
  2163. - (void)share:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2164. {
  2165. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2166. metadataNet.action = actionShare;
  2167. metadataNet.fileID = metadata.fileID;
  2168. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2169. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2170. metadataNet.password = password;
  2171. metadataNet.selector = selectorShare;
  2172. metadataNet.serverUrl = serverUrl;
  2173. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2174. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2175. }
  2176. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2177. {
  2178. [_hud hideHud];
  2179. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2180. // rimuoviamo la condivisione da db
  2181. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup account:appDelegate.activeAccount];
  2182. appDelegate.sharesLink = result[0];
  2183. appDelegate.sharesUserAndGroup = result[1];
  2184. if (_shareOC)
  2185. [_shareOC reloadData];
  2186. [self tableViewReload];
  2187. }
  2188. - (void)unShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl
  2189. {
  2190. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2191. metadataNet.action = actionUnShare;
  2192. metadataNet.fileID = metadata.fileID;
  2193. metadataNet.fileName = metadata.fileName;
  2194. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2195. metadataNet.selector = selectorUnshare;
  2196. metadataNet.serverUrl = serverUrl;
  2197. metadataNet.share = share;
  2198. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2199. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2200. }
  2201. - (void)updateShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2202. {
  2203. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2204. metadataNet.action = actionUpdateShare;
  2205. metadataNet.fileID = metadata.fileID;
  2206. metadataNet.expirationTime = expirationTime;
  2207. metadataNet.password = password;
  2208. metadataNet.selector = selectorUpdateShare;
  2209. metadataNet.serverUrl = serverUrl;
  2210. metadataNet.share = share;
  2211. metadataNet.sharePermission = permission;
  2212. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2213. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2214. }
  2215. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2216. {
  2217. [_hud hideHud];
  2218. if (_shareOC)
  2219. [_shareOC reloadUserAndGroup:items];
  2220. }
  2221. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2222. {
  2223. [_hud hideHud];
  2224. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2225. }
  2226. - (void)getUserAndGroup:(NSString *)find
  2227. {
  2228. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2229. metadataNet.action = actionGetUserAndGroup;
  2230. metadataNet.options = find;
  2231. metadataNet.selector = selectorGetUserAndGroup;
  2232. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2233. [_hud visibleIndeterminateHud];
  2234. }
  2235. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(CCMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2236. {
  2237. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2238. metadataNet.action = actionShareWith;
  2239. metadataNet.fileID = metadata.fileID;
  2240. metadataNet.directoryID = directoryID;
  2241. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2242. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2243. metadataNet.serverUrl = serverUrl;
  2244. metadataNet.selector = selectorShare;
  2245. metadataNet.share = user;
  2246. metadataNet.shareeType = shareeType;
  2247. metadataNet.sharePermission = permission;
  2248. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2249. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2250. }
  2251. - (void)openWindowShare:(CCMetadata *)metadata
  2252. {
  2253. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2254. metadataNet.action = actionReadShareServer;
  2255. metadataNet.fileID = metadata.fileID;
  2256. metadataNet.fileName = metadata.fileName;
  2257. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2258. metadataNet.selector = selectorOpenWindowShare;
  2259. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2260. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2261. [_hud visibleIndeterminateHud];
  2262. }
  2263. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2264. {
  2265. CGPoint location = [tapGesture locationInView:self.tableView];
  2266. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2267. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2268. if (metadata)
  2269. [self openWindowShare:metadata];
  2270. }
  2271. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2272. {
  2273. CGPoint location = [tapGesture locationInView:self.tableView];
  2274. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2275. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2276. if (metadata) {
  2277. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2278. vc.metadata = metadata;
  2279. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2280. [self presentViewController:vc animated:YES completion:nil];
  2281. }
  2282. }
  2283. #pragma --------------------------------------------------------------------------------------------
  2284. #pragma mark ===== Favorite =====
  2285. #pragma --------------------------------------------------------------------------------------------
  2286. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2287. {
  2288. [CCCoreData setMetadataFavoriteFileID:metadataNet.fileID favorite:[metadataNet.options boolValue] activeAccount:app.activeAccount context:nil];
  2289. _dateReadDataSource = nil;
  2290. if (_isSearchMode)
  2291. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2292. else
  2293. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2294. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2295. if (metadata.directory && metadata.favorite) {
  2296. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2297. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2298. }
  2299. }
  2300. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2301. {
  2302. }
  2303. - (void)addFavorite:(CCMetadata *)metadata
  2304. {
  2305. if (metadata.directory) {
  2306. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2307. } else {
  2308. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2309. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2310. }
  2311. }
  2312. - (void)removeFavorite:(CCMetadata *)metadata
  2313. {
  2314. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2315. }
  2316. #pragma --------------------------------------------------------------------------------------------
  2317. #pragma mark ===== Offline =====
  2318. #pragma --------------------------------------------------------------------------------------------
  2319. - (void)addOffline:(CCMetadata *)metadata
  2320. {
  2321. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2322. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2323. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2324. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2325. }
  2326. - (void)removeOffline:(CCMetadata *)metadata
  2327. {
  2328. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2329. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2330. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2331. }
  2332. #pragma --------------------------------------------------------------------------------------------
  2333. #pragma mark ===== Local =====
  2334. #pragma --------------------------------------------------------------------------------------------
  2335. - (void)addLocal:(CCMetadata *)metadata
  2336. {
  2337. if (metadata.errorPasscode || !metadata.uuid) return;
  2338. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2339. if ([metadata.type isEqualToString: k_metadataType_file])
  2340. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2341. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2342. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2343. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2344. }
  2345. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2346. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2347. }
  2348. #pragma --------------------------------------------------------------------------------------------
  2349. #pragma mark ===== Open in... =====
  2350. #pragma --------------------------------------------------------------------------------------------
  2351. - (void)openIn:(CCMetadata *)metadata
  2352. {
  2353. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2354. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2355. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2356. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2357. }
  2358. #pragma --------------------------------------------------------------------------------------------
  2359. #pragma mark ===== Remove Local File =====
  2360. #pragma --------------------------------------------------------------------------------------------
  2361. - (void)removeLocalFile:(CCMetadata *)metadata
  2362. {
  2363. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2364. [CCCoreData deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@)", app.activeAccount, metadata.fileID]];
  2365. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2366. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2367. }
  2368. #pragma --------------------------------------------------------------------------------------------
  2369. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2370. #pragma --------------------------------------------------------------------------------------------
  2371. - (void)orderTable:(NSString *)order
  2372. {
  2373. [CCUtility setOrderSettings:order];
  2374. // Clear data-read of DataSource
  2375. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2376. }
  2377. - (void)ascendingTable:(BOOL)ascending
  2378. {
  2379. [CCUtility setAscendingSettings:ascending];
  2380. // Clear data-read of DataSource
  2381. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2382. }
  2383. - (void)directoryOnTop:(BOOL)directoryOnTop
  2384. {
  2385. [CCUtility setDirectoryOnTop:directoryOnTop];
  2386. // Clear data-read of DataSource
  2387. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2388. }
  2389. - (void)tableGroupBy:(NSString *)groupBy
  2390. {
  2391. [CCUtility setGroupBySettings:groupBy];
  2392. // Clear data-read of DataSource
  2393. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2394. }
  2395. #pragma --------------------------------------------------------------------------------------------
  2396. #pragma mark ==== Menu LOGO ====
  2397. #pragma --------------------------------------------------------------------------------------------
  2398. - (void)menuLogo
  2399. {
  2400. // Test crash
  2401. //[[Crashlytics sharedInstance] crash];
  2402. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2403. return;
  2404. // Brand
  2405. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2406. return;
  2407. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutomaticUploadForAccount:app.activeAccount session:nil] > 0) {
  2408. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2409. return;
  2410. }
  2411. //NSArray *listTableAccount = [CCCoreData getAllTableAccount];
  2412. NSArray *listTableAccount = [[NCManageDatabase sharedInstance] getAccounts:nil];
  2413. NSMutableArray *menuArray = [NSMutableArray new];
  2414. for (TableAccount *record in listTableAccount) {
  2415. if ([record.account isEqualToString:app.activeAccount]) continue;
  2416. CCMenuItem *item = [[CCMenuItem alloc] init];
  2417. item.title = [record.account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2418. item.argument = record.account;
  2419. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2420. item.target = self;
  2421. item.action = @selector(changeDefaultAccount:);
  2422. [menuArray addObject:item];
  2423. }
  2424. if ([menuArray count] == 0)
  2425. return;
  2426. OptionalConfiguration options;
  2427. Color textColor, backgroundColor;
  2428. textColor.R = 0;
  2429. textColor.G = 0;
  2430. textColor.B = 0;
  2431. backgroundColor.R = 1;
  2432. backgroundColor.G = 1;
  2433. backgroundColor.B = 1;
  2434. NSInteger originY = 60;
  2435. options.arrowSize = 9;
  2436. options.marginXSpacing = 7;
  2437. options.marginYSpacing = 10;
  2438. options.intervalSpacing = 20;
  2439. options.menuCornerRadius = 6.5;
  2440. options.maskToBackground = NO;
  2441. options.shadowOfMenu = YES;
  2442. options.hasSeperatorLine = YES;
  2443. options.seperatorLineHasInsets = YES;
  2444. options.textColor = textColor;
  2445. options.menuBackgroundColor = backgroundColor;
  2446. CGRect rect = self.view.frame;
  2447. rect.origin.y = rect.origin.y + originY;
  2448. rect.size.height = rect.size.height - originY;
  2449. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2450. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2451. }
  2452. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2453. {
  2454. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2455. // STOP, erase all in queue networking
  2456. [app cancelAllOperations];
  2457. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2458. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2459. //TableAccount *tableAccount = [CCCoreData setActiveAccount:[sender argument]];
  2460. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2461. if (tableAccount)
  2462. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2463. // go to home sweet home
  2464. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2465. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2466. });
  2467. }
  2468. #pragma --------------------------------------------------------------------------------------------
  2469. #pragma mark ==== ReMenu ====
  2470. #pragma --------------------------------------------------------------------------------------------
  2471. - (void)createReMenuBackgroundView:(REMenu *)menu
  2472. {
  2473. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2474. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2475. [UIView animateWithDuration:0.2 animations:^{
  2476. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2477. if (height < self.tabBarController.tabBar.frame.size.height)
  2478. height = self.tabBarController.tabBar.frame.size.height;
  2479. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2480. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2481. }];
  2482. }
  2483. - (void)createReMainMenu
  2484. {
  2485. NSString *ordinamento;
  2486. NSString *groupBy = _directoryGroupBy;
  2487. __block NSString *nuovoOrdinamento;
  2488. NSString *titoloNuovo, *titoloAttuale;
  2489. BOOL ascendente;
  2490. __block BOOL nuovoAscendente;
  2491. UIImage *image;
  2492. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2493. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2494. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2495. [self tableViewSelect:YES];
  2496. }
  2497. }];
  2498. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2499. ordinamento = _directoryOrder;
  2500. if ([ordinamento isEqualToString:@"fileName"]) {
  2501. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2502. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2503. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2504. nuovoOrdinamento = @"fileDate";
  2505. }
  2506. if ([ordinamento isEqualToString:@"fileDate"]) {
  2507. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2508. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2509. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2510. nuovoOrdinamento = @"fileName";
  2511. }
  2512. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2513. [self orderTable:nuovoOrdinamento];
  2514. }];
  2515. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2516. ascendente = [CCUtility getAscendingSettings];
  2517. if (ascendente) {
  2518. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2519. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2520. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2521. nuovoAscendente = false;
  2522. }
  2523. if (!ascendente) {
  2524. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2525. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2526. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2527. nuovoAscendente = true;
  2528. }
  2529. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2530. [self ascendingTable:nuovoAscendente];
  2531. }];
  2532. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2533. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2534. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2535. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2536. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2537. else [self tableGroupBy:@"alphabetic"];
  2538. }];
  2539. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2540. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2541. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2542. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2543. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2544. else [self tableGroupBy:@"typefile"];
  2545. }];
  2546. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2547. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2548. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2549. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2550. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2551. else [self tableGroupBy:@"date"];
  2552. }];
  2553. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2554. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2555. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2556. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2557. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2558. else [self directoryOnTop:YES];
  2559. }];
  2560. // REMENU --------------------------------------------------------------------------------------------------------------
  2561. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2562. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2563. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2564. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2565. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2566. app.reMainMenu.separatorHeight = 0.5;
  2567. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2568. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2569. app.reMainMenu.textColor = [UIColor blackColor];
  2570. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2571. app.reMainMenu.textShadowColor = nil;
  2572. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2573. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2574. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2575. app.reMainMenu.highlightedSeparatorColor = nil;
  2576. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2577. app.reMainMenu.highlightedTextShadowColor = nil;
  2578. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2579. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2580. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2581. app.reMainMenu.subtitleTextShadowColor = nil;
  2582. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2583. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2584. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2585. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2586. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2587. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2588. app.reMainMenu.borderWidth = 0.3;
  2589. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2590. app.reMainMenu.animationDuration = 0.2;
  2591. app.reMainMenu.closeAnimationDuration = 0.2;
  2592. app.reMainMenu.bounce = NO;
  2593. [app.reMainMenu setClosePreparationBlock:^{
  2594. // Backgroun reMenu (Gesture)
  2595. [_reMenuBackgroundView removeFromSuperview];
  2596. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2597. }];
  2598. }
  2599. - (void)toggleReMainMenu
  2600. {
  2601. if (app.reMainMenu.isOpen) {
  2602. [app.reMainMenu close];
  2603. } else {
  2604. [self createReMainMenu];
  2605. [app.reMainMenu showFromNavigationController:self.navigationController];
  2606. // Backgroun reMenu & (Gesture)
  2607. [self createReMenuBackgroundView:app.reMainMenu];
  2608. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2609. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2610. }
  2611. }
  2612. - (void)createReSelectMenu
  2613. {
  2614. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2615. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2616. [self deleteSelectionFile];
  2617. }];
  2618. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2619. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2620. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2621. }];
  2622. if (app.isCryptoCloudMode) {
  2623. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2624. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2625. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2626. }];
  2627. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2628. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2629. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2630. }];
  2631. }
  2632. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2633. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2634. [self downloadSelectedFiles];
  2635. }];
  2636. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2637. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2638. [self saveSelectedFiles];
  2639. }];
  2640. // REMENU --------------------------------------------------------------------------------------------------------------
  2641. if (app.isCryptoCloudMode) {
  2642. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2643. } else {
  2644. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2645. }
  2646. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2647. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2648. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2649. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2650. app.reSelectMenu.separatorHeight = 0.5;
  2651. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2652. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2653. app.reSelectMenu.textColor = [UIColor blackColor];
  2654. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2655. app.reSelectMenu.textShadowColor = nil;
  2656. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2657. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2658. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2659. app.reSelectMenu.highlightedSeparatorColor = nil;
  2660. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2661. app.reSelectMenu.highlightedTextShadowColor = nil;
  2662. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2663. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2664. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2665. app.reSelectMenu.subtitleTextShadowColor = nil;
  2666. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2667. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2668. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2669. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2670. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2671. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2672. app.reSelectMenu.borderWidth = 0.3;
  2673. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2674. app.reSelectMenu.closeAnimationDuration = 0.2;
  2675. app.reSelectMenu.animationDuration = 0.2;
  2676. app.reSelectMenu.bounce = NO;
  2677. [app.reSelectMenu setClosePreparationBlock:^{
  2678. // Backgroun reMenu (Gesture)
  2679. [_reMenuBackgroundView removeFromSuperview];
  2680. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2681. }];
  2682. }
  2683. - (void)toggleReSelectMenu
  2684. {
  2685. if (app.reSelectMenu.isOpen) {
  2686. [app.reSelectMenu close];
  2687. } else {
  2688. [self createReSelectMenu];
  2689. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2690. // Backgroun reMenu & (Gesture)
  2691. [self createReMenuBackgroundView:app.reSelectMenu];
  2692. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2693. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2694. }
  2695. }
  2696. #pragma --------------------------------------------------------------------------------------------
  2697. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2698. #pragma --------------------------------------------------------------------------------------------
  2699. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2700. {
  2701. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2702. UITableView *tableView = (UITableView*)self.view;
  2703. CGPoint touchPoint = [recognizer locationInView:self.view];
  2704. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2705. if (indexPath)
  2706. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2707. else
  2708. _metadata = nil;
  2709. [self becomeFirstResponder];
  2710. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2711. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2712. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2713. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2714. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2715. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2716. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2717. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2718. if (app.isCryptoCloudMode)
  2719. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2720. else
  2721. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2722. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2723. [menuController setMenuVisible:YES animated:YES];
  2724. }
  2725. }
  2726. - (BOOL)canBecomeFirstResponder
  2727. {
  2728. return YES;
  2729. }
  2730. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2731. {
  2732. // For copy file, copy files, Open in ... :
  2733. //
  2734. // NO Directory
  2735. // NO Error Passcode
  2736. // NO In Session mode (download/upload)
  2737. // NO Template
  2738. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2739. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2740. // NO Cryptated with Title lenght = 0
  2741. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2742. return YES;
  2743. }
  2744. return NO;
  2745. }
  2746. if (@selector(copyFiles:) == action) {
  2747. if (_isSelectedMode) {
  2748. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2749. for (CCMetadata *metadata in selectedMetadatas) {
  2750. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2751. // NO Cryptated with Title lenght = 0
  2752. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2753. return YES;
  2754. }
  2755. }
  2756. }
  2757. return NO;
  2758. }
  2759. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2760. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2761. NSArray *items = [pasteboard items];
  2762. if ([items count] == 1) {
  2763. // Value : (NSData) metadata
  2764. NSDictionary *dic = [items objectAtIndex:0];
  2765. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2766. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2767. //TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2768. NSArray *accounts = [[NCManageDatabase sharedInstance] getAccounts:metadata.account];
  2769. tableAccount *account = [accounts objectAtIndex:0];
  2770. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2771. if (directoryUser) {
  2772. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2773. return YES;
  2774. }
  2775. return NO;
  2776. } else return NO;
  2777. }
  2778. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2779. BOOL isValid = NO;
  2780. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2781. NSArray *items = [pasteboard items];
  2782. if ([items count] <= 1) return NO;
  2783. for (NSDictionary *dic in items) {
  2784. // Value : (NSData) metadata
  2785. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2786. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2787. //TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2788. NSArray *accounts = [[NCManageDatabase sharedInstance] getAccounts:metadata.account];
  2789. tableAccount *account = [accounts objectAtIndex:0];
  2790. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2791. if (directoryUser) {
  2792. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2793. isValid = YES;
  2794. }
  2795. }
  2796. return isValid;
  2797. }
  2798. return NO;
  2799. }
  2800. /************************************ COPY ************************************/
  2801. - (void)copyFile:(id)sender
  2802. {
  2803. // Remove all item
  2804. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2805. pasteboard.items = [[NSArray alloc] init];
  2806. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2807. [self copyFileToPasteboard:_metadata];
  2808. } else {
  2809. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2810. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2811. }
  2812. }
  2813. - (void)copyFiles:(id)sender
  2814. {
  2815. // Remove all item
  2816. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2817. pasteboard.items = [[NSArray alloc] init];
  2818. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2819. for (CCMetadata *metadata in selectedMetadatas) {
  2820. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2821. [self copyFileToPasteboard:metadata];
  2822. } else {
  2823. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2824. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2825. }
  2826. }
  2827. [self tableViewSelect:NO];
  2828. }
  2829. - (void)copyFileToPasteboard:(CCMetadata *)metadata
  2830. {
  2831. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2832. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2833. // Value : (NSData) metadata
  2834. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], k_metadataKeyedUnarchiver,nil];
  2835. [items addObject:item];
  2836. [pasteboard setItems:items];
  2837. }
  2838. /************************************ OPEN IN ... ************************************/
  2839. - (void)openinFile:(id)sender
  2840. {
  2841. [self openIn:_metadata];
  2842. }
  2843. /************************************ PASTE ************************************/
  2844. - (void)pasteFile:(id)sender
  2845. {
  2846. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2847. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2848. }
  2849. - (void)pasteFileEncrypted:(id)sender
  2850. {
  2851. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2852. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2853. }
  2854. - (void)pasteFiles:(id)sender
  2855. {
  2856. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2857. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2858. }
  2859. - (void)pasteFilesEncrypted:(id)sender
  2860. {
  2861. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2862. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2863. }
  2864. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2865. {
  2866. for (NSDictionary *dic in items) {
  2867. // Value : (NSData) metadata
  2868. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2869. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2870. //TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2871. NSArray *accounts = [[NCManageDatabase sharedInstance] getAccounts:metadata.account];
  2872. tableAccount *account = [accounts objectAtIndex:0];
  2873. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2874. if (directoryUser) {
  2875. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2876. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2877. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2878. }
  2879. }
  2880. }
  2881. }
  2882. #pragma --------------------------------------------------------------------------------------------
  2883. #pragma mark ===== Lock Passcode =====
  2884. #pragma --------------------------------------------------------------------------------------------
  2885. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2886. {
  2887. return _failedAttempts;
  2888. }
  2889. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2890. {
  2891. return _lockUntilDate;
  2892. }
  2893. - (void)passcodeViewCloseButtonPressed:(id)sender
  2894. {
  2895. [self dismissViewControllerAnimated:YES completion:nil];
  2896. }
  2897. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2898. {
  2899. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2900. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2901. _lockUntilDate = nil;
  2902. _failedAttempts = 0;
  2903. aResultHandler(YES);
  2904. } else aResultHandler(NO);
  2905. } else aResultHandler(YES);
  2906. }
  2907. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2908. {
  2909. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2910. switch (aViewController.type) {
  2911. case BKPasscodeViewControllerCheckPasscodeType: {
  2912. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2913. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2914. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2915. // scriviamo il passcode
  2916. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2917. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2918. } else {
  2919. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2920. [alertView show];
  2921. }
  2922. }
  2923. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2924. // possiamo procedere alla prossima directory
  2925. [self performSegueDirectoryWithControlPasscode:false];
  2926. // avviamo la sessione Passcode Lock con now
  2927. app.sessionePasscodeLock = [NSDate date];
  2928. }
  2929. // disattivazione lock cartella
  2930. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2931. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2932. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2933. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2934. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2935. }
  2936. [self.tableView reloadData];
  2937. }
  2938. }
  2939. break;
  2940. default:
  2941. break;
  2942. }
  2943. }
  2944. - (void)comandoLockPassword
  2945. {
  2946. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2947. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2948. // se non è abilitato il Lock Passcode esci
  2949. if ([[CCUtility getBlockCode] length] == 0) {
  2950. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2951. [alertView show];
  2952. return;
  2953. }
  2954. // se è richiesta la disattivazione si chiede la password
  2955. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2956. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2957. viewController.delegate = self;
  2958. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2959. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2960. viewController.inputViewTitlePassword = YES;
  2961. if ([CCUtility getSimplyBlockCode]) {
  2962. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2963. viewController.passcodeInputView.maximumLength = 6;
  2964. } else {
  2965. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2966. viewController.passcodeInputView.maximumLength = 64;
  2967. }
  2968. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2969. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2970. viewController.touchIDManager = touchIDManager;
  2971. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2972. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2973. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2974. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2975. [self presentViewController:navigationController animated:YES completion:nil];
  2976. return;
  2977. }
  2978. // ---------------- ACTIVATE PASSWORD
  2979. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2980. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2981. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2982. } else {
  2983. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2984. }
  2985. }
  2986. #pragma mark -
  2987. #pragma --------------------------------------------------------------------------------------------
  2988. #pragma mark ===== Swipe Tablet -> menu =====
  2989. #pragma --------------------------------------------------------------------------------------------
  2990. // more
  2991. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2992. return NSLocalizedString(@"_more_", nil);
  2993. }
  2994. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  2995. {
  2996. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2997. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2998. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder, *titleFavorite;
  2999. BOOL offlineFolder = NO;
  3000. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3001. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3002. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3003. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3004. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3005. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  3006. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3007. offlineFolder = YES;
  3008. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3009. if (_metadata.favorite) {
  3010. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3011. } else {
  3012. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3013. }
  3014. if (_metadata.directory) {
  3015. // calcolo lockServerUrl
  3016. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3017. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3018. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3019. }
  3020. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:_metadata.fileID activeAccount:app.activeAccount];
  3021. /******************************************* AHKActionSheet *******************************************/
  3022. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3023. actionSheet.animationDuration = 0.2;
  3024. actionSheet.blurRadius = 0.0f;
  3025. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3026. actionSheet.buttonHeight = 50.0;
  3027. actionSheet.cancelButtonHeight = 50.0f;
  3028. actionSheet.separatorHeight = 5.0f;
  3029. actionSheet.automaticallyTintButtonImages = @(NO);
  3030. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3031. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3032. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3033. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3034. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3035. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3036. /******************************************* DIRECTORY *******************************************/
  3037. if (_metadata.directory) {
  3038. BOOL lockDirectory = NO;
  3039. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3040. // Directory bloccata ?
  3041. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3042. //NSString *cameraUploadFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount];
  3043. //NSString *cameraUploadFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3044. NSString *cameraUploadFolderName = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderName];
  3045. NSString *cameraUploadFolderPath = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  3046. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3047. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3048. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3049. height: 50.0
  3050. type: AHKActionSheetButtonTypeDisabled
  3051. handler: nil
  3052. ];
  3053. if (!lockDirectory && !_metadata.cryptated) {
  3054. [actionSheet addButtonWithTitle:titleFavorite
  3055. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3056. backgroundColor:[UIColor whiteColor]
  3057. height: 50.0
  3058. type:AHKActionSheetButtonTypeDefault
  3059. handler:^(AHKActionSheet *as) {
  3060. // close swipe
  3061. [self setEditing:NO animated:YES];
  3062. if (_metadata.favorite)
  3063. [self removeFavorite:_metadata];
  3064. else
  3065. [self addFavorite:_metadata];
  3066. }];
  3067. }
  3068. if (_metadata.cryptated == NO && !lockDirectory) {
  3069. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3070. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3071. backgroundColor:[UIColor whiteColor]
  3072. height: 50.0
  3073. type:AHKActionSheetButtonTypeDefault
  3074. handler:^(AHKActionSheet *as) {
  3075. // close swipe
  3076. [self setEditing:NO animated:YES];
  3077. [self openWindowShare:_metadata];
  3078. }];
  3079. }
  3080. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3081. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3082. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3083. backgroundColor:[UIColor whiteColor]
  3084. height: 50.0
  3085. type:AHKActionSheetButtonTypeDefault
  3086. handler:^(AHKActionSheet *as) {
  3087. // close swipe
  3088. [self setEditing:NO animated:YES];
  3089. //chiediamo il nome del file
  3090. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3091. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3092. alertView.tag = alertRename;
  3093. UITextField *textField = [alertView textFieldAtIndex:0];
  3094. textField.text = _metadata.fileNamePrint;
  3095. [alertView show];
  3096. }];
  3097. }
  3098. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3099. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3100. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3101. backgroundColor:[UIColor whiteColor]
  3102. height: 50.0
  3103. type:AHKActionSheetButtonTypeDefault
  3104. handler:^(AHKActionSheet *as) {
  3105. // close swipe
  3106. [self setEditing:NO animated:YES];
  3107. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3108. }];
  3109. }
  3110. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3111. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3112. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3113. backgroundColor:[UIColor whiteColor]
  3114. height: 50.0
  3115. type:AHKActionSheetButtonTypeDefault
  3116. handler:^(AHKActionSheet *as) {
  3117. // close swipe
  3118. [self setEditing:NO animated:YES];
  3119. // Settings new folder Automatatic upload
  3120. // NSString *oldPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3121. NSString *oldPath = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  3122. //[CCCoreData setCameraUploadFolderName:_metadata.fileName activeAccount:app.activeAccount];
  3123. //[CCCoreData setCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl activeAccount:app.activeAccount];
  3124. [[NCManageDatabase sharedInstance] setAccountsCameraUploadFolderNameWithFolderName:_metadata.fileName];
  3125. [[NCManageDatabase sharedInstance] setAccountsCameraUploadFolderPathWithPathName:serverUrl activeUrl:app.activeUrl];
  3126. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:oldPath directoryID:nil];
  3127. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3128. [app.activePhotosCameraUpload reloadDatasourceForced];
  3129. [self readFolderWithForced:YES serverUrl:serverUrl];
  3130. NSLog(@"[LOG] Update Folder Photo");
  3131. //NSString *folderCameraUpload = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3132. NSString *folderCameraUpload = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathAndName:app.activeUrl];
  3133. if ([folderCameraUpload length] > 0)
  3134. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[CCCoreData getDirectoryIDFromServerUrl:folderCameraUpload activeAccount:app.activeAccount] selector:selectorReadFolder];
  3135. }];
  3136. }
  3137. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3138. [actionSheet addButtonWithTitle:titoloLock
  3139. image:[UIImage imageNamed:@"actionSheetLock"]
  3140. backgroundColor:[UIColor whiteColor]
  3141. height: 50.0
  3142. type:AHKActionSheetButtonTypeEncrypted
  3143. handler:^(AHKActionSheet *as) {
  3144. // close swipe
  3145. [self setEditing:NO animated:YES];
  3146. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3147. }];
  3148. }
  3149. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3150. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3151. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3152. backgroundColor:[UIColor whiteColor]
  3153. height: 50.0
  3154. type:AHKActionSheetButtonTypeEncrypted
  3155. handler:^(AHKActionSheet *as) {
  3156. // close swipe
  3157. [self setEditing:NO animated:YES];
  3158. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3159. }];
  3160. }
  3161. [actionSheet show];
  3162. }
  3163. /******************************************* FILE *******************************************/
  3164. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3165. UIImage *iconHeader;
  3166. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3167. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3168. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3169. else
  3170. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3171. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3172. image: iconHeader
  3173. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3174. height: 50.0
  3175. type: AHKActionSheetButtonTypeDisabled
  3176. handler: nil
  3177. ];
  3178. if (!_metadata.cryptated) {
  3179. [actionSheet addButtonWithTitle:titleFavorite
  3180. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3181. backgroundColor:[UIColor whiteColor]
  3182. height: 50.0
  3183. type:AHKActionSheetButtonTypeDefault
  3184. handler:^(AHKActionSheet *as) {
  3185. // close swipe
  3186. [self setEditing:NO animated:YES];
  3187. if (_metadata.favorite)
  3188. [self removeFavorite:_metadata];
  3189. else
  3190. [self addFavorite:_metadata];
  3191. }];
  3192. }
  3193. if (_metadata.cryptated == NO) {
  3194. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3195. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3196. backgroundColor:[UIColor whiteColor]
  3197. height: 50.0
  3198. type:AHKActionSheetButtonTypeDefault
  3199. handler:^(AHKActionSheet *as) {
  3200. // close swipe
  3201. [self setEditing:NO animated:YES];
  3202. [self openWindowShare:_metadata];
  3203. }];
  3204. }
  3205. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3206. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3207. backgroundColor:[UIColor whiteColor]
  3208. height: 50.0
  3209. type:AHKActionSheetButtonTypeDefault
  3210. handler:^(AHKActionSheet *as) {
  3211. // close swipe
  3212. [self setEditing:NO animated:YES];
  3213. [self performSelector:@selector(openIn:) withObject:_metadata];
  3214. }];
  3215. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3216. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3217. backgroundColor:[UIColor whiteColor]
  3218. height: 50.0
  3219. type:AHKActionSheetButtonTypeDefault
  3220. handler:^(AHKActionSheet *as) {
  3221. // close swipe
  3222. [self setEditing:NO animated:YES];
  3223. //chiediamo il nome del file
  3224. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3225. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3226. alertView.tag = alertRename;
  3227. UITextField *textField = [alertView textFieldAtIndex:0];
  3228. textField.text = _metadata.fileNamePrint;
  3229. [alertView show];
  3230. }];
  3231. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3232. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3233. backgroundColor:[UIColor whiteColor]
  3234. height: 50.0
  3235. type:AHKActionSheetButtonTypeDefault
  3236. handler:^(AHKActionSheet *as) {
  3237. // close swipe
  3238. [self setEditing:NO animated:YES];
  3239. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3240. }];
  3241. if (recordLocalFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3242. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3243. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3244. backgroundColor:[UIColor whiteColor]
  3245. height: 50.0
  3246. type:AHKActionSheetButtonTypeDefault
  3247. handler:^(AHKActionSheet *as) {
  3248. // close swipe
  3249. [self setEditing:NO animated:YES];
  3250. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3251. }];
  3252. }
  3253. if (app.isCryptoCloudMode) {
  3254. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3255. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3256. backgroundColor:[UIColor whiteColor]
  3257. height: 50.0
  3258. type:AHKActionSheetButtonTypeEncrypted
  3259. handler:^(AHKActionSheet *as) {
  3260. // close swipe
  3261. [self setEditing:NO animated:YES];
  3262. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3263. }];
  3264. }
  3265. [actionSheet show];
  3266. }
  3267. /******************************************* TEMPLATE *******************************************/
  3268. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3269. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3270. image: [UIImage imageNamed:_metadata.iconName]
  3271. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3272. height: 50.0
  3273. type: AHKActionSheetButtonTypeDisabled
  3274. handler: nil
  3275. ];
  3276. if ([_metadata.model isEqualToString:@"note"]) {
  3277. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3278. image:[UIImage imageNamed:@"actionSheetRename"]
  3279. backgroundColor:[UIColor whiteColor]
  3280. height: 50.0
  3281. type:AHKActionSheetButtonTypeDefault
  3282. handler:^(AHKActionSheet *as) {
  3283. // close swipe
  3284. [self setEditing:NO animated:YES];
  3285. //chiediamo il nome del file
  3286. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3287. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3288. alertView.tag = alertRename;
  3289. UITextField *textField = [alertView textFieldAtIndex:0];
  3290. textField.text = _metadata.fileNamePrint;
  3291. [alertView show];
  3292. }];
  3293. }
  3294. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3295. image:[UIImage imageNamed:@"actionSheetMove"]
  3296. backgroundColor:[UIColor whiteColor]
  3297. height: 50.0
  3298. type:AHKActionSheetButtonTypeDefault
  3299. handler:^(AHKActionSheet *as) {
  3300. // close swipe
  3301. [self setEditing:NO animated:YES];
  3302. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3303. }];
  3304. [actionSheet show];
  3305. }
  3306. }
  3307. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3308. {
  3309. return NSLocalizedString(@"_delete_", nil);
  3310. }
  3311. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3312. {
  3313. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3314. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3315. else return YES;
  3316. }
  3317. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3318. {
  3319. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3320. if (metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3321. else return UITableViewCellEditingStyleDelete;
  3322. }
  3323. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3324. {
  3325. BOOL lockDirectory = NO;
  3326. // Directory locked ?
  3327. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account] addFileName:_metadata.fileNameData];
  3328. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3329. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3330. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3331. return;
  3332. }
  3333. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3334. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3335. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3336. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3337. style:UIAlertActionStyleDestructive
  3338. handler:^(UIAlertAction *action) {
  3339. [self performSelector:@selector(deleteFile) withObject:nil];
  3340. }]];
  3341. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3342. style:UIAlertActionStyleCancel
  3343. handler:^(UIAlertAction *action) {
  3344. [alertController dismissViewControllerAnimated:YES completion:nil];
  3345. }]];
  3346. alertController.popoverPresentationController.sourceView = self.view;
  3347. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3348. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3349. [alertController.view layoutIfNeeded];
  3350. [self presentViewController:alertController animated:YES completion:nil];
  3351. }
  3352. }
  3353. #pragma --------------------------------------------------------------------------------------------
  3354. #pragma mark - ==== Datasource ====
  3355. #pragma --------------------------------------------------------------------------------------------
  3356. - (void)clearDateReadDataSource:(NSNotification *)notification
  3357. {
  3358. _dateReadDataSource = Nil;
  3359. [self reloadDatasource];
  3360. }
  3361. - (void)reloadDatasource
  3362. {
  3363. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3364. }
  3365. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3366. {
  3367. // test
  3368. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3369. return;
  3370. // Search Mode
  3371. if(_isSearchMode) {
  3372. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3373. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3374. } else {
  3375. [self readFolderWithForced:NO serverUrl:serverUrl];
  3376. }
  3377. [self tableViewReload];
  3378. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3379. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3380. _noFilesSearchDescription = @"";
  3381. }
  3382. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3383. _noFilesSearchTitle = @"";
  3384. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3385. }
  3386. [self.tableView reloadEmptyDataSet];
  3387. return;
  3388. }
  3389. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3390. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3391. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3392. [app.activeTransfers reloadDatasource];
  3393. } else {
  3394. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3395. if (main) {
  3396. [main reloadDatasource];
  3397. } else {
  3398. [self tableViewReload];
  3399. [app.activeTransfers reloadDatasource];
  3400. }
  3401. }
  3402. return;
  3403. }
  3404. // Offline folder ?
  3405. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3406. [app.activeTransfers reloadDatasource];
  3407. // Settaggio variabili per le ottimizzazioni
  3408. _directoryGroupBy = [CCUtility getGroupBySettings];
  3409. _directoryOrder = [CCUtility getOrderSettings];
  3410. // Controllo data lettura Data Source
  3411. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3412. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3413. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3414. _dateReadDataSource = [NSDate date];
  3415. // Data Source
  3416. NSArray *recordsTableMetadata = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] fieldOrder:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3417. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3418. } else {
  3419. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3420. }
  3421. [self tableViewReload];
  3422. }
  3423. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3424. {
  3425. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3426. if (selectedRows.count > 0) {
  3427. for (NSIndexPath *selectionIndex in selectedRows) {
  3428. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3429. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3430. [metadatas addObject:metadata];
  3431. }
  3432. }
  3433. return metadatas;
  3434. }
  3435. - (CCMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3436. {
  3437. NSInteger section = indexPath.section + 1;
  3438. NSInteger row = indexPath.row + 1;
  3439. NSInteger totSections =[_sectionDataSource.sections count] ;
  3440. if ((totSections < section) || (section > totSections)) {
  3441. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3442. return nil;
  3443. }
  3444. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3445. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3446. if (fileIDs) {
  3447. NSInteger totRows =[fileIDs count] ;
  3448. if ((totRows < row) || (row > totRows)) {
  3449. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3450. return nil;
  3451. }
  3452. } else {
  3453. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3454. return nil;
  3455. }
  3456. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3457. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3458. }
  3459. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3460. {
  3461. NSInteger totSections =[_sectionDataSource.sections count] ;
  3462. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3463. #if DEBUG
  3464. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3465. [alertView show];
  3466. #endif
  3467. return nil;
  3468. }
  3469. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3470. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3471. }
  3472. #pragma --------------------------------------------------------------------------------------------
  3473. #pragma mark - ==== Table ====
  3474. #pragma --------------------------------------------------------------------------------------------
  3475. - (void)tableViewSelect:(BOOL)edit
  3476. {
  3477. // chiudiamo eventuali swipe aperti
  3478. if (edit) [self.tableView setEditing:NO animated:NO];
  3479. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3480. [self.tableView setEditing:edit animated:YES];
  3481. _isSelectedMode = edit;
  3482. if (edit)
  3483. [self setUINavigationBarSelected];
  3484. else
  3485. [self setUINavigationBarDefault];
  3486. [self setTitle];
  3487. }
  3488. - (void)tableViewReload
  3489. {
  3490. // ricordiamoci le row selezionate
  3491. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3492. [self.tableView reloadData];
  3493. for (NSIndexPath *path in indexPaths)
  3494. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3495. [self setTableViewFooter];
  3496. if (self.tableView.editing)
  3497. [self setTitle];
  3498. }
  3499. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3500. {
  3501. return 60;
  3502. }
  3503. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3504. {
  3505. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3506. }
  3507. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3508. {
  3509. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3510. }
  3511. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3512. {
  3513. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3514. NSString *sectionTitle = [sections objectAtIndex:section];
  3515. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3516. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3517. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3518. return 20.f;
  3519. }
  3520. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3521. {
  3522. float shift;
  3523. UIVisualEffectView *visualEffectView;
  3524. // Titolo
  3525. NSString *titleSection;
  3526. // Controllo
  3527. if ([_sectionDataSource.sections count] == 0)
  3528. return nil;
  3529. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3530. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3531. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3532. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3533. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3534. else titleSection = NSLocalizedString(titleSection,nil);
  3535. // Formato titolo
  3536. NSString *currentDevice = [CCUtility currentDevice];
  3537. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3538. visualEffectView = [[UIVisualEffectView alloc] init];
  3539. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3540. } else {
  3541. UIVisualEffect *blurEffect;
  3542. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3543. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3544. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3545. }
  3546. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3547. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3548. else shift = - 20;
  3549. } else shift = - 10;
  3550. // Title
  3551. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3552. titleLabel.backgroundColor = [UIColor clearColor];
  3553. titleLabel.textColor = [UIColor blackColor];
  3554. titleLabel.font = [UIFont systemFontOfSize:12];
  3555. titleLabel.textAlignment = NSTextAlignmentLeft;
  3556. titleLabel.text = titleSection;
  3557. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3558. [visualEffectView addSubview:titleLabel];
  3559. // Elements
  3560. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3561. elementLabel.backgroundColor = [UIColor clearColor];
  3562. elementLabel.textColor = [UIColor blackColor];;
  3563. elementLabel.font = [UIFont systemFontOfSize:12];
  3564. elementLabel.textAlignment = NSTextAlignmentRight;
  3565. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3566. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3567. NSUInteger rowsCount = [metadatas count];
  3568. if (rowsCount == 0) return nil;
  3569. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3570. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3571. [visualEffectView addSubview:elementLabel];
  3572. return visualEffectView;
  3573. }
  3574. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3575. {
  3576. return [_sectionDataSource.sections indexOfObject:title];
  3577. }
  3578. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3579. {
  3580. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3581. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3582. else
  3583. return nil;
  3584. }
  3585. /*
  3586. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3587. {
  3588. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3589. }
  3590. }
  3591. */
  3592. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3593. {
  3594. NSString *typeCell;
  3595. NSString *dataFile;
  3596. NSString *lunghezzaFile;
  3597. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3598. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3599. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3600. else typeCell = @"CellMainTransfer";
  3601. if (!metadata)
  3602. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3603. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3604. // separator
  3605. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3606. // change color selection
  3607. UIView *selectionColor = [[UIView alloc] init];
  3608. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3609. cell.selectedBackgroundView = selectionColor;
  3610. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3611. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3612. // ----------------------------------------------------------------------------------------------------------
  3613. // DEFAULT
  3614. // ----------------------------------------------------------------------------------------------------------
  3615. cell.fileImageView.image = nil;
  3616. cell.statusImageView.image = nil;
  3617. cell.offlineImageView.image = nil;
  3618. cell.synchronizedImageView.image = nil;
  3619. cell.sharedImageView.image = nil;
  3620. cell.labelTitle.enabled = YES;
  3621. cell.labelTitle.text = @"";
  3622. cell.labelInfoFile.enabled = YES;
  3623. cell.labelInfoFile.text = @"";
  3624. cell.progressView.progress = 0.0;
  3625. cell.progressView.hidden = YES;
  3626. cell.cancelTaskButton.hidden = YES;
  3627. cell.reloadTaskButton.hidden = YES;
  3628. cell.stopTaskButton.hidden = YES;
  3629. // Encrypted color
  3630. if (metadata.cryptated) {
  3631. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3632. } else {
  3633. cell.labelTitle.textColor = [UIColor blackColor];
  3634. }
  3635. // ----------------------------------------------------------------------------------------------------------
  3636. // File Name & Folder
  3637. // ----------------------------------------------------------------------------------------------------------
  3638. // nome del file
  3639. cell.labelTitle.text = metadata.fileNamePrint;
  3640. // è una directory
  3641. if (metadata.directory) {
  3642. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3643. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3644. lunghezzaFile = @" ";
  3645. // ----------------------------------------------------------------------------------------------------------
  3646. // Favorite Folder
  3647. // ----------------------------------------------------------------------------------------------------------
  3648. if (metadata.favorite) {
  3649. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3650. }
  3651. } else {
  3652. // File
  3653. dataFile = [CCUtility dateDiff:metadata.date];
  3654. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3655. // Plist ancora da scaricare
  3656. if (metadata.cryptated && [metadata.title length] == 0) {
  3657. dataFile = @" ";
  3658. lunghezzaFile = @" ";
  3659. }
  3660. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3661. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3662. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3663. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3664. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3665. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3666. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3667. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3668. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3669. else
  3670. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3671. }
  3672. // Plist ancora da scaricare
  3673. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3674. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3675. cell.accessoryType = UITableViewCellAccessoryNone;
  3676. }
  3677. // ----------------------------------------------------------------------------------------------------------
  3678. // File Image View
  3679. // ----------------------------------------------------------------------------------------------------------
  3680. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3681. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3682. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3683. if (cell.fileImageView.image == nil) {
  3684. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3685. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3686. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  3687. dispatch_async(dispatch_get_main_queue(), ^{
  3688. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3689. if (cell)
  3690. cell.fileImageView.image = image;
  3691. });
  3692. });
  3693. }
  3694. } else {
  3695. if (metadata.directory)
  3696. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3697. else
  3698. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3699. if (metadata.thumbnailExists)
  3700. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3701. }
  3702. // ----------------------------------------------------------------------------------------------------------
  3703. // Image Status cyptated & Lock Passcode
  3704. // ----------------------------------------------------------------------------------------------------------
  3705. // File Cyptated
  3706. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3707. cell.statusImageView.image = [UIImage imageNamed:@"lock"];
  3708. }
  3709. // Directory con passcode lock attivato
  3710. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3711. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length]))
  3712. cell.statusImageView.image = [UIImage imageNamed:@"passcode"];
  3713. // ----------------------------------------------------------------------------------------------------------
  3714. // Offline
  3715. // ----------------------------------------------------------------------------------------------------------
  3716. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3717. if (isOfflineFile) {
  3718. cell.offlineImageView.image = [UIImage imageNamed:@"offline"];
  3719. }
  3720. // ----------------------------------------------------------------------------------------------------------
  3721. // Favorite
  3722. // ----------------------------------------------------------------------------------------------------------
  3723. if (metadata.favorite) {
  3724. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3725. }
  3726. // ----------------------------------------------------------------------------------------------------------
  3727. // Share
  3728. // ----------------------------------------------------------------------------------------------------------
  3729. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3730. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3731. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3732. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3733. // Aggiungiamo il Tap per le shared
  3734. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3735. if (isShare) {
  3736. if (metadata.directory) {
  3737. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3738. cell.sharedImageView.userInteractionEnabled = NO;
  3739. } else {
  3740. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3741. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3742. [tap setNumberOfTapsRequired:1];
  3743. cell.sharedImageView.userInteractionEnabled = YES;
  3744. [cell.sharedImageView addGestureRecognizer:tap];
  3745. }
  3746. }
  3747. if (isMounted) {
  3748. if (metadata.directory) {
  3749. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3750. cell.sharedImageView.userInteractionEnabled = NO;
  3751. } else {
  3752. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3753. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3754. [tap setNumberOfTapsRequired:1];
  3755. cell.sharedImageView.userInteractionEnabled = YES;
  3756. [cell.sharedImageView addGestureRecognizer:tap];
  3757. }
  3758. }
  3759. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3760. if (metadata.directory) {
  3761. if ([shareLink length] > 0)
  3762. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3763. if ([shareUserAndGroup length] > 0)
  3764. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3765. cell.sharedImageView.userInteractionEnabled = NO;
  3766. } else {
  3767. if ([shareLink length] > 0)
  3768. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3769. if ([shareUserAndGroup length] > 0)
  3770. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3771. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3772. [tap setNumberOfTapsRequired:1];
  3773. cell.sharedImageView.userInteractionEnabled = YES;
  3774. [cell.sharedImageView addGestureRecognizer:tap];
  3775. }
  3776. }
  3777. } else {
  3778. cell.sharedImageView.userInteractionEnabled = NO;
  3779. }
  3780. // ----------------------------------------------------------------------------------------------------------
  3781. // downloadFile
  3782. // ----------------------------------------------------------------------------------------------------------
  3783. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3784. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3785. else cell.statusImageView.image = [UIImage imageNamed:@"statusdownload"];
  3786. // sessionTaskIdentifier : RELOAD + STOP
  3787. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3788. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3789. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3790. cell.cancelTaskButton.hidden = NO;
  3791. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3792. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3793. cell.reloadTaskButton.hidden = NO;
  3794. }
  3795. // sessionTaskIdentifierPlist : RELOAD
  3796. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3797. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3798. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3799. cell.reloadTaskButton.hidden = NO;
  3800. }
  3801. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3802. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3803. if (progress > 0) {
  3804. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3805. else cell.progressView.progressTintColor = [UIColor blackColor];
  3806. cell.progressView.progress = progress;
  3807. cell.progressView.hidden = NO;
  3808. }
  3809. // ----------------------------------------------------------------------------------------------------------
  3810. // downloadFile Error
  3811. // ----------------------------------------------------------------------------------------------------------
  3812. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3813. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3814. if ([metadata.sessionError length] == 0)
  3815. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3816. else
  3817. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3818. }
  3819. }
  3820. // ----------------------------------------------------------------------------------------------------------
  3821. // uploadFile
  3822. // ----------------------------------------------------------------------------------------------------------
  3823. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3824. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3825. else cell.statusImageView.image = [UIImage imageNamed:@"statusupload"];
  3826. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3827. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3828. cell.cancelTaskButton.hidden = NO;
  3829. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3830. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3831. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3832. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusstopcrypto"];
  3833. else cell.statusImageView.image = [UIImage imageNamed:@"statusstop"];
  3834. cell.reloadTaskButton.hidden = NO;
  3835. cell.stopTaskButton.hidden = YES;
  3836. } else {
  3837. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3838. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3839. cell.stopTaskButton.hidden = NO;
  3840. cell.reloadTaskButton.hidden = YES;
  3841. }
  3842. // se non c'è una preview in bianconero metti l'immagine di default
  3843. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3844. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3845. cell.labelTitle.enabled = NO;
  3846. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3847. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3848. if (progress > 0) {
  3849. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3850. else cell.progressView.progressTintColor = [UIColor blackColor];
  3851. cell.progressView.progress = progress;
  3852. cell.progressView.hidden = NO;
  3853. }
  3854. // ----------------------------------------------------------------------------------------------------------
  3855. // uploadFileError
  3856. // ----------------------------------------------------------------------------------------------------------
  3857. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3858. cell.labelTitle.enabled = NO;
  3859. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3860. if ([metadata.sessionError length] == 0)
  3861. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3862. else
  3863. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3864. }
  3865. }
  3866. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3867. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3868. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3869. return cell;
  3870. }
  3871. - (void)setTableViewFooter
  3872. {
  3873. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3874. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3875. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3876. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3877. UIFont *appFont = [UIFont systemFontOfSize:12];
  3878. footerLabel.font = appFont;
  3879. footerLabel.textColor = [UIColor grayColor];
  3880. footerLabel.backgroundColor = [UIColor clearColor];
  3881. footerLabel.textAlignment = NSTextAlignmentCenter;
  3882. NSString *folders;
  3883. NSString *files;
  3884. NSString *footerText;
  3885. if (_sectionDataSource.directories > 1) {
  3886. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3887. } else if (_sectionDataSource.directories == 1){
  3888. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3889. } else {
  3890. folders = @"";
  3891. }
  3892. if (_sectionDataSource.files > 1) {
  3893. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3894. } else if (_sectionDataSource.files == 1){
  3895. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3896. } else {
  3897. files = @"";
  3898. }
  3899. if ([folders isEqualToString:@""]) {
  3900. footerText = files;
  3901. } else if ([files isEqualToString:@""]) {
  3902. footerText = folders;
  3903. } else {
  3904. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3905. }
  3906. footerLabel.text = footerText;
  3907. [footerView addSubview:footerLabel];
  3908. [self.tableView setTableFooterView:footerView];
  3909. }
  3910. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3911. {
  3912. NSString *textMessage;
  3913. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3914. // se non può essere selezionata deseleziona
  3915. if ([cell isEditing] == NO)
  3916. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3917. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3918. if (self.tableView.editing) {
  3919. [self setTitle];
  3920. return;
  3921. }
  3922. // test crash
  3923. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3924. if (indexPath.row >= [metadatas count]) return;
  3925. // settiamo il record file.
  3926. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3927. //
  3928. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3929. // se è in corso una sessione
  3930. if ([_metadata.session length] > 0) return;
  3931. if (_metadata.errorPasscode) {
  3932. // se UUID è nil lo sta ancora caricando quindi esci
  3933. if (!_metadata.uuid) return;
  3934. // esiste un hint ??
  3935. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3936. // qui !! la richiesta della nuova passcode
  3937. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3938. // stesso UUID ... la password è stata modificata !!!!!!
  3939. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3940. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3941. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3942. [alertView show];
  3943. } else {
  3944. // UUID diverso.
  3945. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3946. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3947. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3948. [alertView show];
  3949. }
  3950. // chiediamo la passcode e ricarichiamo tutto.
  3951. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3952. viewController.delegate = self;
  3953. viewController.fromType = CCBKPasscodeFromPasscode;
  3954. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3955. viewController.passcodeInputView.maximumLength = 64;
  3956. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3957. viewController.inputViewTitlePassword = NO;
  3958. viewController.title = [NCBrandOptions sharedInstance].brand;
  3959. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3960. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3961. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3962. [self presentViewController:navigationController animated:YES completion:nil];
  3963. }
  3964. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3965. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3966. NSString* selector;
  3967. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3968. else selector = selectorLoadPlist;
  3969. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3970. return;
  3971. }
  3972. // se il plist è caricato ed è un modello aprilo
  3973. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3974. // file
  3975. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3976. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3977. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3978. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3979. } else {
  3980. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3981. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3982. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3983. }
  3984. }
  3985. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3986. }
  3987. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3988. {
  3989. [self setTitle];
  3990. }
  3991. #pragma --------------------------------------------------------------------------------------------
  3992. #pragma mark ===== Synchronize Folder Cell =====
  3993. #pragma --------------------------------------------------------------------------------------------
  3994. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3995. {
  3996. BOOL cryptated = NO;
  3997. CCCellMain *cell;
  3998. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3999. CCMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4000. if (recordMetadata.directory == NO)
  4001. continue;
  4002. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  4003. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  4004. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  4005. cryptated = recordMetadata.cryptated;
  4006. break;
  4007. }
  4008. }
  4009. if (!cell)
  4010. return;
  4011. if (animation) {
  4012. NSURL *myURL;
  4013. if (cryptated)
  4014. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  4015. else
  4016. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  4017. } else {
  4018. cell.synchronizedImageView.image = nil;
  4019. }
  4020. }
  4021. #pragma --------------------------------------------------------------------------------------------
  4022. #pragma mark ===== Navigation ====
  4023. #pragma --------------------------------------------------------------------------------------------
  4024. - (BOOL)shouldPerformSegue
  4025. {
  4026. // if background return
  4027. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4028. if (self.view.window == NO)
  4029. return NO;
  4030. // Collapsed ma siamo già in detail esci
  4031. if (self.splitViewController.isCollapsed)
  4032. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4033. // Video in esecuzione esci
  4034. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4035. return YES;
  4036. }
  4037. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4038. {
  4039. id viewController = segue.destinationViewController;
  4040. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4041. CCMetadata *metadata;
  4042. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4043. UINavigationController *nav = viewController;
  4044. _detailViewController = (CCDetail *)nav.topViewController;
  4045. } else {
  4046. _detailViewController = segue.destinationViewController;
  4047. }
  4048. if ([sender isKindOfClass:[CCMetadata class]]) {
  4049. metadata = sender;
  4050. [allRecordsDataSourceImagesVideos addObject:sender];
  4051. } else {
  4052. metadata = _metadata;
  4053. for (NSString *fileID in _sectionDataSource.allFileID) {
  4054. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4055. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4056. [allRecordsDataSourceImagesVideos addObject:metadata];
  4057. }
  4058. }
  4059. _detailViewController.metadataDetail = metadata;
  4060. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4061. _detailViewController.dateFilterQuery = nil;
  4062. _detailViewController.isCameraUpload = NO;
  4063. [_detailViewController setTitle:metadata.fileNamePrint];
  4064. }
  4065. // can i go to next viewcontroller
  4066. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4067. {
  4068. NSString *nomeDir;
  4069. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4070. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4071. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4072. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4073. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4074. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4075. viewController.delegate = self;
  4076. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4077. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4078. viewController.inputViewTitlePassword = YES;
  4079. if ([CCUtility getSimplyBlockCode]) {
  4080. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4081. viewController.passcodeInputView.maximumLength = 6;
  4082. } else {
  4083. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4084. viewController.passcodeInputView.maximumLength = 64;
  4085. }
  4086. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4087. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4088. viewController.touchIDManager = touchIDManager;
  4089. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4090. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4091. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4092. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4093. [self presentViewController:navController animated:YES completion:nil];
  4094. return;
  4095. }
  4096. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4097. else nomeDir = _metadata.fileName;
  4098. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4099. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4100. if (viewController.isViewLoaded == false || viewController == nil) {
  4101. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4102. viewController.isFolderEncrypted = _metadata.cryptated;
  4103. viewController.serverUrl = serverUrlPush;
  4104. viewController.titleMain = _metadata.fileNamePrint;
  4105. viewController.textBackButton = _titleMain;
  4106. // save self
  4107. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4108. }
  4109. // OFF SearchBar
  4110. [viewController cancelSearchBar];
  4111. [self.navigationController pushViewController:viewController animated:YES];
  4112. }
  4113. }
  4114. @end