CCMain.m 250 KB

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